repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/VisualBasic/Portable/Lowering/MethodToClassRewriter/MethodToClassRewriter.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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A bound node rewriter that rewrites types properly (which in some cases the automatically-generated). ''' This is used in the lambda rewriter, the iterator rewriter, and the async rewriter. ''' </summary> Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy) Inherits BoundTreeRewriterWithStackGuard ''' <summary> ''' For each captured variable, the corresponding field of its frame ''' </summary> Protected ReadOnly Proxies As Dictionary(Of Symbol, TProxy) = New Dictionary(Of Symbol, TProxy)() ''' <summary> ''' A mapping from every local variable to its replacement local variable. Local variables ''' are replaced when their types change due to being inside of a lambda within a generic method. ''' </summary> Protected ReadOnly LocalMap As Dictionary(Of LocalSymbol, LocalSymbol) = New Dictionary(Of LocalSymbol, LocalSymbol)(ReferenceEqualityComparer.Instance) ''' <summary> ''' A mapping from every parameter to its replacement parameter. Local variables ''' are replaced when their types change due to being inside of a lambda. ''' </summary> Protected ReadOnly ParameterMap As Dictionary(Of ParameterSymbol, ParameterSymbol) = New Dictionary(Of ParameterSymbol, ParameterSymbol)(ReferenceEqualityComparer.Instance) Protected ReadOnly PlaceholderReplacementMap As New Dictionary(Of BoundValuePlaceholderBase, BoundExpression) ''' <summary> ''' The mapping of type parameters for the current lambda body ''' </summary> Protected MustOverride ReadOnly Property TypeMap As TypeSubstitution Friend MustOverride Function FramePointer(syntax As SyntaxNode, frameClass As NamedTypeSymbol) As BoundExpression ''' <summary> ''' The method (e.g. lambda) which is currently being rewritten. If we are ''' rewriting a lambda, currentMethod is the new generated method. ''' </summary> Protected MustOverride ReadOnly Property CurrentMethod As MethodSymbol Protected MustOverride ReadOnly Property TopLevelMethod As MethodSymbol Protected MustOverride ReadOnly Property IsInExpressionLambda As Boolean ''' <summary> ''' A not-null collection of synthesized methods generated for the current source type. ''' </summary> Protected ReadOnly CompilationState As TypeCompilationState Protected ReadOnly Diagnostics As BindingDiagnosticBag Protected ReadOnly SlotAllocatorOpt As VariableSlotAllocator ''' <summary> ''' During rewriting, we ignore locals that have already been rewritten to a proxy (a field on a closure class). ''' However, in the EE, we need to preserve the original slots for all locals (slots for any new locals must be ''' appended after the originals). The <see cref="PreserveOriginalLocals"/> field is intended to suppress any ''' rewriter logic that would result in original locals being omitted. ''' </summary> Protected ReadOnly PreserveOriginalLocals As Boolean Protected Sub New(slotAllocatorOpt As VariableSlotAllocator, compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, preserveOriginalLocals As Boolean) Debug.Assert(compilationState IsNot Nothing) Debug.Assert(diagnostics.AccumulatesDiagnostics) Me.CompilationState = compilationState Me.Diagnostics = diagnostics Me.SlotAllocatorOpt = slotAllocatorOpt Me.PreserveOriginalLocals = preserveOriginalLocals End Sub #Region "Visitors" Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode Dim localSymbol = node.LocalSymbol Dim proxy As TProxy = Nothing If Proxies.TryGetValue(localSymbol, proxy) Then ' Constant locals are never captured. Debug.Assert(Not localSymbol.IsConst) Return Nothing End If Return node End Function Public NotOverridable Overrides Function VisitType(type As TypeSymbol) As TypeSymbol If type Is Nothing Then Return type End If Return type.InternalSubstituteTypeParameters(Me.TypeMap).Type End Function Public NotOverridable Overrides Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode Return node.Update(VisitMethodSymbol(node.Method), VisitType(node.Type)) End Function Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode ' NOTE: this is only reachable from Lambda rewriter ' NOTE: in case property access is inside expression tree Dim rewrittenPropertySymbol = VisitPropertySymbol(node.PropertySymbol) Dim rewrittenReceiver = DirectCast(Visit(node.ReceiverOpt), BoundExpression) Dim arguments As ImmutableArray(Of BoundExpression) = node.Arguments Dim newArguments(arguments.Length - 1) As BoundExpression For i = 0 To arguments.Length - 1 newArguments(i) = DirectCast(Visit(arguments(i)), BoundExpression) Next Return node.Update(rewrittenPropertySymbol, Nothing, node.AccessKind, isWriteable:=node.IsWriteable, isLValue:=node.IsLValue, receiverOpt:=rewrittenReceiver, arguments:=newArguments.AsImmutableOrNull, defaultArguments:=node.DefaultArguments, type:=VisitType(node.Type)) End Function Public Overrides Function VisitCall(node As BoundCall) As BoundNode Dim receiverOpt As BoundExpression = node.ReceiverOpt Dim rewrittenReceiverOpt As BoundExpression = DirectCast(Visit(receiverOpt), BoundExpression) Dim newMethod As MethodSymbol = node.Method Dim arguments As ImmutableArray(Of BoundExpression) = VisitList(node.Arguments) Dim type As TypeSymbol = VisitType(node.Type) If ShouldRewriteMethodSymbol(receiverOpt, rewrittenReceiverOpt, newMethod) Then Dim methodBeingCalled As MethodSymbol = SubstituteMethodForMyBaseOrMyClassCall(receiverOpt, node.Method) newMethod = VisitMethodSymbol(methodBeingCalled) End If Return node.Update(newMethod, Nothing, rewrittenReceiverOpt, arguments, node.DefaultArguments, node.ConstantValueOpt, isLValue:=node.IsLValue, suppressObjectClone:=node.SuppressObjectClone, type:=type) End Function Private Function ShouldRewriteMethodSymbol(originalReceiver As BoundExpression, rewrittenReceiverOpt As BoundExpression, newMethod As MethodSymbol) As Boolean Return originalReceiver IsNot rewrittenReceiverOpt OrElse Not newMethod.IsDefinition OrElse (Me.TypeMap IsNot Nothing AndAlso Me.TypeMap.TargetGenericDefinition.Equals(newMethod)) OrElse (Me.IsInExpressionLambda AndAlso rewrittenReceiverOpt IsNot Nothing AndAlso (rewrittenReceiverOpt.IsMyClassReference OrElse rewrittenReceiverOpt.IsMyBaseReference)) End Function Public NotOverridable Overrides Function VisitParameter(node As BoundParameter) As BoundNode Dim proxy As TProxy = Nothing If Proxies.TryGetValue(node.ParameterSymbol, proxy) Then Return Me.MaterializeProxy(node, proxy) End If Dim replacementParameter As ParameterSymbol = Nothing If Me.ParameterMap.TryGetValue(node.ParameterSymbol, replacementParameter) Then Return New BoundParameter(node.Syntax, replacementParameter, node.IsLValue, replacementParameter.Type, node.HasErrors) End If Return MyBase.VisitParameter(node) End Function Protected MustOverride Function MaterializeProxy(origExpression As BoundExpression, proxy As TProxy) As BoundNode Public NotOverridable Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local As LocalSymbol = node.LocalSymbol If local.IsConst Then ' Local constants are never captured Return MyBase.VisitLocal(node) End If Dim proxy As TProxy = Nothing If Proxies.TryGetValue(local, proxy) Then Return Me.MaterializeProxy(node, proxy) End If Dim replacementLocal As LocalSymbol = Nothing If Me.LocalMap.TryGetValue(local, replacementLocal) Then Return New BoundLocal(node.Syntax, replacementLocal, node.IsLValue, replacementLocal.Type, node.HasErrors) End If Return MyBase.VisitLocal(node) End Function Public Overrides Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode Return node.Update(VisitFieldSymbol(node.Field), VisitType(node.Type)) End Function Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Return node.Update(DirectCast(Visit(node.ReceiverOpt), BoundExpression), VisitFieldSymbol(node.FieldSymbol), node.IsLValue, node.SuppressVirtualCalls, constantsInProgressOpt:=Nothing, VisitType(node.Type)) End Function Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode Debug.Assert(node.RelaxationLambdaOpt Is Nothing AndAlso node.RelaxationReceiverPlaceholderOpt Is Nothing) Dim rewritten = DirectCast(MyBase.VisitDelegateCreationExpression(node), BoundDelegateCreationExpression) Dim newMethod As MethodSymbol = rewritten.Method Dim rewrittenReceiver As BoundExpression = rewritten.ReceiverOpt If ShouldRewriteMethodSymbol(node.ReceiverOpt, rewrittenReceiver, newMethod) Then Dim methodBeingCalled As MethodSymbol = SubstituteMethodForMyBaseOrMyClassCall(node.ReceiverOpt, node.Method) newMethod = VisitMethodSymbol(methodBeingCalled) End If Return node.Update( rewrittenReceiver, newMethod, rewritten.RelaxationLambdaOpt, rewritten.RelaxationReceiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=rewritten.Type) End Function Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode Dim rewritten = DirectCast(MyBase.VisitObjectCreationExpression(node), BoundObjectCreationExpression) Dim constructor = rewritten.ConstructorOpt If constructor IsNot Nothing Then If node.Type IsNot rewritten.Type OrElse Not constructor.IsDefinition Then Dim newConstructor = VisitMethodSymbol(constructor) rewritten = node.Update( newConstructor, rewritten.Arguments, rewritten.DefaultArguments, rewritten.InitializerOpt, rewritten.Type) End If End If Return rewritten End Function ''' <summary> ''' Rewrites method. ''' </summary> Private Function VisitMethodSymbol(method As MethodSymbol) As MethodSymbol Dim substitution As TypeSubstitution = Me.TypeMap If substitution IsNot Nothing Then Dim newMethod As MethodSymbol = method.OriginalDefinition Dim newContainer As TypeSymbol = method.ContainingType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly() Dim substitutedContainer = TryCast(newContainer, SubstitutedNamedType) If substitutedContainer IsNot Nothing Then newMethod = DirectCast(substitutedContainer.GetMemberForDefinition(newMethod), MethodSymbol) Else Dim anonymousContainer = TryCast(newContainer, AnonymousTypeManager.AnonymousTypeOrDelegatePublicSymbol) If anonymousContainer IsNot Nothing Then newMethod = anonymousContainer.FindSubstitutedMethodSymbol(newMethod) End If End If If newMethod.IsGenericMethod Then Dim typeArgs = method.TypeArguments Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol For i = 0 To typeArgs.Length - 1 visitedTypeArgs(i) = VisitType(typeArgs(i)) Next newMethod = newMethod.Construct(visitedTypeArgs) End If Return newMethod End If Return method End Function ''' <summary> ''' Rewrites property. ''' </summary> Private Function VisitPropertySymbol([property] As PropertySymbol) As PropertySymbol Dim substitution As TypeSubstitution = Me.TypeMap If substitution IsNot Nothing Then Dim newProperty As PropertySymbol = [property].OriginalDefinition Dim newContainer As TypeSymbol = [property].ContainingType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly() Dim substitutedContainer = TryCast(newContainer, SubstitutedNamedType) If substitutedContainer IsNot Nothing Then newProperty = DirectCast(substitutedContainer.GetMemberForDefinition(newProperty), PropertySymbol) Else Dim anonymousContainer = TryCast(newContainer, AnonymousTypeManager.AnonymousTypePublicSymbol) If anonymousContainer IsNot Nothing Then Dim anonProperty = TryCast(newProperty, AnonymousTypeManager.AnonymousTypePropertyPublicSymbol) newProperty = anonymousContainer.Properties(anonProperty.PropertyIndex) End If End If Return newProperty End If Return [property] End Function ''' <summary> ''' Rewrites field. ''' </summary> Private Function VisitFieldSymbol(field As FieldSymbol) As FieldSymbol Dim substitution As TypeSubstitution = Me.TypeMap If substitution IsNot Nothing Then Dim newField As FieldSymbol = field.OriginalDefinition Dim newContainer As TypeSymbol = field.ContainingType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly() Dim substitutedContainer = TryCast(newContainer, SubstitutedNamedType) If substitutedContainer IsNot Nothing Then newField = DirectCast(substitutedContainer.GetMemberForDefinition(newField), FieldSymbol) End If Return newField End If Return field End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Return RewriteBlock(node) End Function Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode Return RewriteSequence(node) End Function Public MustOverride Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode Protected Function RewriteBlock(node As BoundBlock, prologue As ArrayBuilder(Of BoundExpression), newLocals As ArrayBuilder(Of LocalSymbol)) As BoundBlock For Each v In node.Locals If Me.PreserveOriginalLocals OrElse Not Me.Proxies.ContainsKey(v) Then Dim vType = VisitType(v.Type) If TypeSymbol.Equals(vType, v.Type, TypeCompareKind.ConsiderEverything) Then Dim replacement As LocalSymbol = Nothing Dim wasReplaced As Boolean = False If Not LocalMap.TryGetValue(v, replacement) Then replacement = CreateReplacementLocalOrReturnSelf(v, vType, onlyReplaceIfFunctionValue:=True, wasReplaced:=wasReplaced) End If If wasReplaced Then LocalMap.Add(v, replacement) End If newLocals.Add(replacement) Else Dim replacement As LocalSymbol = CreateReplacementLocalOrReturnSelf(v, vType) newLocals.Add(replacement) LocalMap.Add(v, replacement) End If End If Next Dim newStatements = ArrayBuilder(Of BoundStatement).GetInstance Dim start As Integer = 0 Dim nodeStatements = node.Statements If prologue.Count > 0 Then ' Add hidden sequence point, prologue doesn't map to source, but if ' the first statement in the block is a non-hidden sequence point ' (for example, sequence point for a method block), keep it first. If nodeStatements.Length > 0 AndAlso nodeStatements(0).Syntax IsNot Nothing Then Dim keepSequencePointFirst As Boolean = False Select Case nodeStatements(0).Kind Case BoundKind.SequencePoint Dim sp = DirectCast(nodeStatements(0), BoundSequencePoint) keepSequencePointFirst = sp.StatementOpt Is Nothing Case BoundKind.SequencePointWithSpan Dim sp = DirectCast(nodeStatements(0), BoundSequencePointWithSpan) keepSequencePointFirst = sp.StatementOpt Is Nothing End Select If keepSequencePointFirst Then Dim replacement = DirectCast(Me.Visit(nodeStatements(0)), BoundStatement) If replacement IsNot Nothing Then newStatements.Add(replacement) End If start = 1 End If End If newStatements.Add(New BoundSequencePoint(Nothing, Nothing).MakeCompilerGenerated) End If For Each expr In prologue newStatements.Add(New BoundExpressionStatement(expr.Syntax, expr)) Next ' done with this prologue.Free() For i As Integer = start To nodeStatements.Length - 1 Dim replacement = DirectCast(Me.Visit(nodeStatements(i)), BoundStatement) If replacement IsNot Nothing Then newStatements.Add(replacement) End If Next 'TODO: we may not need to update if there was nothing to rewrite. Return node.Update(node.StatementListSyntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree()) End Function Protected Function RewriteBlock(node As BoundBlock) As BoundBlock Dim prologue = ArrayBuilder(Of BoundExpression).GetInstance Dim newLocals = ArrayBuilder(Of LocalSymbol).GetInstance Return RewriteBlock(node, prologue, newLocals) End Function Protected Shared Function CreateReplacementLocalOrReturnSelf( originalLocal As LocalSymbol, newType As TypeSymbol, Optional onlyReplaceIfFunctionValue As Boolean = False, <Out()> Optional ByRef wasReplaced As Boolean = False ) As LocalSymbol If Not onlyReplaceIfFunctionValue OrElse originalLocal.IsFunctionValue Then wasReplaced = True Return LocalSymbol.Create(originalLocal, newType) Else wasReplaced = False Return originalLocal End If End Function Protected Function RewriteSequence(node As BoundSequence) As BoundSequence Dim prologue = ArrayBuilder(Of BoundExpression).GetInstance Dim newLocals = ArrayBuilder(Of LocalSymbol).GetInstance Return RewriteSequence(node, prologue, newLocals) End Function Protected Function RewriteSequence(node As BoundSequence, prologue As ArrayBuilder(Of BoundExpression), newLocals As ArrayBuilder(Of LocalSymbol)) As BoundSequence Dim origLocals = node.Locals ' merge locals new and rewritten original For Each v In origLocals If Not Me.Proxies.ContainsKey(v) Then Dim vType = VisitType(v.Type) If TypeSymbol.Equals(vType, v.Type, TypeCompareKind.ConsiderEverything) Then newLocals.Add(v) Else Dim replacement = CreateReplacementLocalOrReturnSelf(v, vType) newLocals.Add(replacement) LocalMap.Add(v, replacement) End If End If Next ' merge side-effect - prologue followed by rewritten original side-effect For Each s In node.SideEffects Dim replacement = DirectCast(Me.Visit(s), BoundExpression) If replacement IsNot Nothing Then prologue.Add(replacement) End If Next Debug.Assert(node.ValueOpt IsNot Nothing OrElse node.HasErrors OrElse node.Type.SpecialType = SpecialType.System_Void) Dim newValue = DirectCast(Me.Visit(node.ValueOpt), BoundExpression) Return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, If(newValue Is Nothing, node.Type, newValue.Type)) End Function Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode Return PlaceholderReplacementMap(node) End Function Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode Return PlaceholderReplacementMap(node) End Function Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode Dim awaitablePlaceholder As BoundRValuePlaceholder = node.AwaitableInstancePlaceholder PlaceholderReplacementMap.Add(awaitablePlaceholder, awaitablePlaceholder.Update(VisitType(awaitablePlaceholder.Type))) Dim awaiterPlaceholder As BoundLValuePlaceholder = node.AwaiterInstancePlaceholder PlaceholderReplacementMap.Add(awaiterPlaceholder, awaiterPlaceholder.Update(VisitType(awaiterPlaceholder.Type))) Dim result As BoundNode = MyBase.VisitAwaitOperator(node) PlaceholderReplacementMap.Remove(awaitablePlaceholder) PlaceholderReplacementMap.Remove(awaiterPlaceholder) Return result End Function Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode Dim placeholder As BoundRValuePlaceholder = node.ExprPlaceholderOpt If placeholder IsNot Nothing Then PlaceholderReplacementMap.Add(placeholder, placeholder.Update(VisitType(placeholder.Type))) End If Dim result As BoundNode = MyBase.VisitSelectStatement(node) If placeholder IsNot Nothing Then PlaceholderReplacementMap.Remove(placeholder) End If Return result End Function Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode Dim leftOperandPlaceholder As BoundRValuePlaceholder = node.LeftOperandPlaceholder PlaceholderReplacementMap.Add(leftOperandPlaceholder, leftOperandPlaceholder.Update(VisitType(leftOperandPlaceholder.Type))) Dim result As BoundNode = MyBase.VisitUserDefinedShortCircuitingOperator(node) PlaceholderReplacementMap.Remove(leftOperandPlaceholder) Return result End Function #End Region 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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A bound node rewriter that rewrites types properly (which in some cases the automatically-generated). ''' This is used in the lambda rewriter, the iterator rewriter, and the async rewriter. ''' </summary> Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy) Inherits BoundTreeRewriterWithStackGuard ''' <summary> ''' For each captured variable, the corresponding field of its frame ''' </summary> Protected ReadOnly Proxies As Dictionary(Of Symbol, TProxy) = New Dictionary(Of Symbol, TProxy)() ''' <summary> ''' A mapping from every local variable to its replacement local variable. Local variables ''' are replaced when their types change due to being inside of a lambda within a generic method. ''' </summary> Protected ReadOnly LocalMap As Dictionary(Of LocalSymbol, LocalSymbol) = New Dictionary(Of LocalSymbol, LocalSymbol)(ReferenceEqualityComparer.Instance) ''' <summary> ''' A mapping from every parameter to its replacement parameter. Local variables ''' are replaced when their types change due to being inside of a lambda. ''' </summary> Protected ReadOnly ParameterMap As Dictionary(Of ParameterSymbol, ParameterSymbol) = New Dictionary(Of ParameterSymbol, ParameterSymbol)(ReferenceEqualityComparer.Instance) Protected ReadOnly PlaceholderReplacementMap As New Dictionary(Of BoundValuePlaceholderBase, BoundExpression) ''' <summary> ''' The mapping of type parameters for the current lambda body ''' </summary> Protected MustOverride ReadOnly Property TypeMap As TypeSubstitution Friend MustOverride Function FramePointer(syntax As SyntaxNode, frameClass As NamedTypeSymbol) As BoundExpression ''' <summary> ''' The method (e.g. lambda) which is currently being rewritten. If we are ''' rewriting a lambda, currentMethod is the new generated method. ''' </summary> Protected MustOverride ReadOnly Property CurrentMethod As MethodSymbol Protected MustOverride ReadOnly Property TopLevelMethod As MethodSymbol Protected MustOverride ReadOnly Property IsInExpressionLambda As Boolean ''' <summary> ''' A not-null collection of synthesized methods generated for the current source type. ''' </summary> Protected ReadOnly CompilationState As TypeCompilationState Protected ReadOnly Diagnostics As BindingDiagnosticBag Protected ReadOnly SlotAllocatorOpt As VariableSlotAllocator ''' <summary> ''' During rewriting, we ignore locals that have already been rewritten to a proxy (a field on a closure class). ''' However, in the EE, we need to preserve the original slots for all locals (slots for any new locals must be ''' appended after the originals). The <see cref="PreserveOriginalLocals"/> field is intended to suppress any ''' rewriter logic that would result in original locals being omitted. ''' </summary> Protected ReadOnly PreserveOriginalLocals As Boolean Protected Sub New(slotAllocatorOpt As VariableSlotAllocator, compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, preserveOriginalLocals As Boolean) Debug.Assert(compilationState IsNot Nothing) Debug.Assert(diagnostics.AccumulatesDiagnostics) Me.CompilationState = compilationState Me.Diagnostics = diagnostics Me.SlotAllocatorOpt = slotAllocatorOpt Me.PreserveOriginalLocals = preserveOriginalLocals End Sub #Region "Visitors" Public Overrides Function VisitLocalDeclaration(node As BoundLocalDeclaration) As BoundNode Dim localSymbol = node.LocalSymbol Dim proxy As TProxy = Nothing If Proxies.TryGetValue(localSymbol, proxy) Then ' Constant locals are never captured. Debug.Assert(Not localSymbol.IsConst) Return Nothing End If Return node End Function Public NotOverridable Overrides Function VisitType(type As TypeSymbol) As TypeSymbol If type Is Nothing Then Return type End If Return type.InternalSubstituteTypeParameters(Me.TypeMap).Type End Function Public NotOverridable Overrides Function VisitMethodInfo(node As BoundMethodInfo) As BoundNode Return node.Update(VisitMethodSymbol(node.Method), VisitType(node.Type)) End Function Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode ' NOTE: this is only reachable from Lambda rewriter ' NOTE: in case property access is inside expression tree Dim rewrittenPropertySymbol = VisitPropertySymbol(node.PropertySymbol) Dim rewrittenReceiver = DirectCast(Visit(node.ReceiverOpt), BoundExpression) Dim arguments As ImmutableArray(Of BoundExpression) = node.Arguments Dim newArguments(arguments.Length - 1) As BoundExpression For i = 0 To arguments.Length - 1 newArguments(i) = DirectCast(Visit(arguments(i)), BoundExpression) Next Return node.Update(rewrittenPropertySymbol, Nothing, node.AccessKind, isWriteable:=node.IsWriteable, isLValue:=node.IsLValue, receiverOpt:=rewrittenReceiver, arguments:=newArguments.AsImmutableOrNull, defaultArguments:=node.DefaultArguments, type:=VisitType(node.Type)) End Function Public Overrides Function VisitCall(node As BoundCall) As BoundNode Dim receiverOpt As BoundExpression = node.ReceiverOpt Dim rewrittenReceiverOpt As BoundExpression = DirectCast(Visit(receiverOpt), BoundExpression) Dim newMethod As MethodSymbol = node.Method Dim arguments As ImmutableArray(Of BoundExpression) = VisitList(node.Arguments) Dim type As TypeSymbol = VisitType(node.Type) If ShouldRewriteMethodSymbol(receiverOpt, rewrittenReceiverOpt, newMethod) Then Dim methodBeingCalled As MethodSymbol = SubstituteMethodForMyBaseOrMyClassCall(receiverOpt, node.Method) newMethod = VisitMethodSymbol(methodBeingCalled) End If Return node.Update(newMethod, Nothing, rewrittenReceiverOpt, arguments, node.DefaultArguments, node.ConstantValueOpt, isLValue:=node.IsLValue, suppressObjectClone:=node.SuppressObjectClone, type:=type) End Function Private Function ShouldRewriteMethodSymbol(originalReceiver As BoundExpression, rewrittenReceiverOpt As BoundExpression, newMethod As MethodSymbol) As Boolean Return originalReceiver IsNot rewrittenReceiverOpt OrElse Not newMethod.IsDefinition OrElse (Me.TypeMap IsNot Nothing AndAlso Me.TypeMap.TargetGenericDefinition.Equals(newMethod)) OrElse (Me.IsInExpressionLambda AndAlso rewrittenReceiverOpt IsNot Nothing AndAlso (rewrittenReceiverOpt.IsMyClassReference OrElse rewrittenReceiverOpt.IsMyBaseReference)) End Function Public NotOverridable Overrides Function VisitParameter(node As BoundParameter) As BoundNode Dim proxy As TProxy = Nothing If Proxies.TryGetValue(node.ParameterSymbol, proxy) Then Return Me.MaterializeProxy(node, proxy) End If Dim replacementParameter As ParameterSymbol = Nothing If Me.ParameterMap.TryGetValue(node.ParameterSymbol, replacementParameter) Then Return New BoundParameter(node.Syntax, replacementParameter, node.IsLValue, replacementParameter.Type, node.HasErrors) End If Return MyBase.VisitParameter(node) End Function Protected MustOverride Function MaterializeProxy(origExpression As BoundExpression, proxy As TProxy) As BoundNode Public NotOverridable Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local As LocalSymbol = node.LocalSymbol If local.IsConst Then ' Local constants are never captured Return MyBase.VisitLocal(node) End If Dim proxy As TProxy = Nothing If Proxies.TryGetValue(local, proxy) Then Return Me.MaterializeProxy(node, proxy) End If Dim replacementLocal As LocalSymbol = Nothing If Me.LocalMap.TryGetValue(local, replacementLocal) Then Return New BoundLocal(node.Syntax, replacementLocal, node.IsLValue, replacementLocal.Type, node.HasErrors) End If Return MyBase.VisitLocal(node) End Function Public Overrides Function VisitFieldInfo(node As BoundFieldInfo) As BoundNode Return node.Update(VisitFieldSymbol(node.Field), VisitType(node.Type)) End Function Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Return node.Update(DirectCast(Visit(node.ReceiverOpt), BoundExpression), VisitFieldSymbol(node.FieldSymbol), node.IsLValue, node.SuppressVirtualCalls, constantsInProgressOpt:=Nothing, VisitType(node.Type)) End Function Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode Debug.Assert(node.RelaxationLambdaOpt Is Nothing AndAlso node.RelaxationReceiverPlaceholderOpt Is Nothing) Dim rewritten = DirectCast(MyBase.VisitDelegateCreationExpression(node), BoundDelegateCreationExpression) Dim newMethod As MethodSymbol = rewritten.Method Dim rewrittenReceiver As BoundExpression = rewritten.ReceiverOpt If ShouldRewriteMethodSymbol(node.ReceiverOpt, rewrittenReceiver, newMethod) Then Dim methodBeingCalled As MethodSymbol = SubstituteMethodForMyBaseOrMyClassCall(node.ReceiverOpt, node.Method) newMethod = VisitMethodSymbol(methodBeingCalled) End If Return node.Update( rewrittenReceiver, newMethod, rewritten.RelaxationLambdaOpt, rewritten.RelaxationReceiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=rewritten.Type) End Function Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode Dim rewritten = DirectCast(MyBase.VisitObjectCreationExpression(node), BoundObjectCreationExpression) Dim constructor = rewritten.ConstructorOpt If constructor IsNot Nothing Then If node.Type IsNot rewritten.Type OrElse Not constructor.IsDefinition Then Dim newConstructor = VisitMethodSymbol(constructor) rewritten = node.Update( newConstructor, rewritten.Arguments, rewritten.DefaultArguments, rewritten.InitializerOpt, rewritten.Type) End If End If Return rewritten End Function ''' <summary> ''' Rewrites method. ''' </summary> Private Function VisitMethodSymbol(method As MethodSymbol) As MethodSymbol Dim substitution As TypeSubstitution = Me.TypeMap If substitution IsNot Nothing Then Dim newMethod As MethodSymbol = method.OriginalDefinition Dim newContainer As TypeSymbol = method.ContainingType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly() Dim substitutedContainer = TryCast(newContainer, SubstitutedNamedType) If substitutedContainer IsNot Nothing Then newMethod = DirectCast(substitutedContainer.GetMemberForDefinition(newMethod), MethodSymbol) Else Dim anonymousContainer = TryCast(newContainer, AnonymousTypeManager.AnonymousTypeOrDelegatePublicSymbol) If anonymousContainer IsNot Nothing Then newMethod = anonymousContainer.FindSubstitutedMethodSymbol(newMethod) End If End If If newMethod.IsGenericMethod Then Dim typeArgs = method.TypeArguments Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol For i = 0 To typeArgs.Length - 1 visitedTypeArgs(i) = VisitType(typeArgs(i)) Next newMethod = newMethod.Construct(visitedTypeArgs) End If Return newMethod End If Return method End Function ''' <summary> ''' Rewrites property. ''' </summary> Private Function VisitPropertySymbol([property] As PropertySymbol) As PropertySymbol Dim substitution As TypeSubstitution = Me.TypeMap If substitution IsNot Nothing Then Dim newProperty As PropertySymbol = [property].OriginalDefinition Dim newContainer As TypeSymbol = [property].ContainingType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly() Dim substitutedContainer = TryCast(newContainer, SubstitutedNamedType) If substitutedContainer IsNot Nothing Then newProperty = DirectCast(substitutedContainer.GetMemberForDefinition(newProperty), PropertySymbol) Else Dim anonymousContainer = TryCast(newContainer, AnonymousTypeManager.AnonymousTypePublicSymbol) If anonymousContainer IsNot Nothing Then Dim anonProperty = TryCast(newProperty, AnonymousTypeManager.AnonymousTypePropertyPublicSymbol) newProperty = anonymousContainer.Properties(anonProperty.PropertyIndex) End If End If Return newProperty End If Return [property] End Function ''' <summary> ''' Rewrites field. ''' </summary> Private Function VisitFieldSymbol(field As FieldSymbol) As FieldSymbol Dim substitution As TypeSubstitution = Me.TypeMap If substitution IsNot Nothing Then Dim newField As FieldSymbol = field.OriginalDefinition Dim newContainer As TypeSymbol = field.ContainingType.InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly() Dim substitutedContainer = TryCast(newContainer, SubstitutedNamedType) If substitutedContainer IsNot Nothing Then newField = DirectCast(substitutedContainer.GetMemberForDefinition(newField), FieldSymbol) End If Return newField End If Return field End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Return RewriteBlock(node) End Function Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode Return RewriteSequence(node) End Function Public MustOverride Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode Protected Function RewriteBlock(node As BoundBlock, prologue As ArrayBuilder(Of BoundExpression), newLocals As ArrayBuilder(Of LocalSymbol)) As BoundBlock For Each v In node.Locals If Me.PreserveOriginalLocals OrElse Not Me.Proxies.ContainsKey(v) Then Dim vType = VisitType(v.Type) If TypeSymbol.Equals(vType, v.Type, TypeCompareKind.ConsiderEverything) Then Dim replacement As LocalSymbol = Nothing Dim wasReplaced As Boolean = False If Not LocalMap.TryGetValue(v, replacement) Then replacement = CreateReplacementLocalOrReturnSelf(v, vType, onlyReplaceIfFunctionValue:=True, wasReplaced:=wasReplaced) End If If wasReplaced Then LocalMap.Add(v, replacement) End If newLocals.Add(replacement) Else Dim replacement As LocalSymbol = CreateReplacementLocalOrReturnSelf(v, vType) newLocals.Add(replacement) LocalMap.Add(v, replacement) End If End If Next Dim newStatements = ArrayBuilder(Of BoundStatement).GetInstance Dim start As Integer = 0 Dim nodeStatements = node.Statements If prologue.Count > 0 Then ' Add hidden sequence point, prologue doesn't map to source, but if ' the first statement in the block is a non-hidden sequence point ' (for example, sequence point for a method block), keep it first. If nodeStatements.Length > 0 AndAlso nodeStatements(0).Syntax IsNot Nothing Then Dim keepSequencePointFirst As Boolean = False Select Case nodeStatements(0).Kind Case BoundKind.SequencePoint Dim sp = DirectCast(nodeStatements(0), BoundSequencePoint) keepSequencePointFirst = sp.StatementOpt Is Nothing Case BoundKind.SequencePointWithSpan Dim sp = DirectCast(nodeStatements(0), BoundSequencePointWithSpan) keepSequencePointFirst = sp.StatementOpt Is Nothing End Select If keepSequencePointFirst Then Dim replacement = DirectCast(Me.Visit(nodeStatements(0)), BoundStatement) If replacement IsNot Nothing Then newStatements.Add(replacement) End If start = 1 End If End If newStatements.Add(New BoundSequencePoint(Nothing, Nothing).MakeCompilerGenerated) End If For Each expr In prologue newStatements.Add(New BoundExpressionStatement(expr.Syntax, expr)) Next ' done with this prologue.Free() For i As Integer = start To nodeStatements.Length - 1 Dim replacement = DirectCast(Me.Visit(nodeStatements(i)), BoundStatement) If replacement IsNot Nothing Then newStatements.Add(replacement) End If Next 'TODO: we may not need to update if there was nothing to rewrite. Return node.Update(node.StatementListSyntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree()) End Function Protected Function RewriteBlock(node As BoundBlock) As BoundBlock Dim prologue = ArrayBuilder(Of BoundExpression).GetInstance Dim newLocals = ArrayBuilder(Of LocalSymbol).GetInstance Return RewriteBlock(node, prologue, newLocals) End Function Protected Shared Function CreateReplacementLocalOrReturnSelf( originalLocal As LocalSymbol, newType As TypeSymbol, Optional onlyReplaceIfFunctionValue As Boolean = False, <Out()> Optional ByRef wasReplaced As Boolean = False ) As LocalSymbol If Not onlyReplaceIfFunctionValue OrElse originalLocal.IsFunctionValue Then wasReplaced = True Return LocalSymbol.Create(originalLocal, newType) Else wasReplaced = False Return originalLocal End If End Function Protected Function RewriteSequence(node As BoundSequence) As BoundSequence Dim prologue = ArrayBuilder(Of BoundExpression).GetInstance Dim newLocals = ArrayBuilder(Of LocalSymbol).GetInstance Return RewriteSequence(node, prologue, newLocals) End Function Protected Function RewriteSequence(node As BoundSequence, prologue As ArrayBuilder(Of BoundExpression), newLocals As ArrayBuilder(Of LocalSymbol)) As BoundSequence Dim origLocals = node.Locals ' merge locals new and rewritten original For Each v In origLocals If Not Me.Proxies.ContainsKey(v) Then Dim vType = VisitType(v.Type) If TypeSymbol.Equals(vType, v.Type, TypeCompareKind.ConsiderEverything) Then newLocals.Add(v) Else Dim replacement = CreateReplacementLocalOrReturnSelf(v, vType) newLocals.Add(replacement) LocalMap.Add(v, replacement) End If End If Next ' merge side-effect - prologue followed by rewritten original side-effect For Each s In node.SideEffects Dim replacement = DirectCast(Me.Visit(s), BoundExpression) If replacement IsNot Nothing Then prologue.Add(replacement) End If Next Debug.Assert(node.ValueOpt IsNot Nothing OrElse node.HasErrors OrElse node.Type.SpecialType = SpecialType.System_Void) Dim newValue = DirectCast(Me.Visit(node.ValueOpt), BoundExpression) Return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, If(newValue Is Nothing, node.Type, newValue.Type)) End Function Public Overrides Function VisitRValuePlaceholder(node As BoundRValuePlaceholder) As BoundNode Return PlaceholderReplacementMap(node) End Function Public Overrides Function VisitLValuePlaceholder(node As BoundLValuePlaceholder) As BoundNode Return PlaceholderReplacementMap(node) End Function Public Overrides Function VisitAwaitOperator(node As BoundAwaitOperator) As BoundNode Dim awaitablePlaceholder As BoundRValuePlaceholder = node.AwaitableInstancePlaceholder PlaceholderReplacementMap.Add(awaitablePlaceholder, awaitablePlaceholder.Update(VisitType(awaitablePlaceholder.Type))) Dim awaiterPlaceholder As BoundLValuePlaceholder = node.AwaiterInstancePlaceholder PlaceholderReplacementMap.Add(awaiterPlaceholder, awaiterPlaceholder.Update(VisitType(awaiterPlaceholder.Type))) Dim result As BoundNode = MyBase.VisitAwaitOperator(node) PlaceholderReplacementMap.Remove(awaitablePlaceholder) PlaceholderReplacementMap.Remove(awaiterPlaceholder) Return result End Function Public Overrides Function VisitSelectStatement(node As BoundSelectStatement) As BoundNode Dim placeholder As BoundRValuePlaceholder = node.ExprPlaceholderOpt If placeholder IsNot Nothing Then PlaceholderReplacementMap.Add(placeholder, placeholder.Update(VisitType(placeholder.Type))) End If Dim result As BoundNode = MyBase.VisitSelectStatement(node) If placeholder IsNot Nothing Then PlaceholderReplacementMap.Remove(placeholder) End If Return result End Function Public Overrides Function VisitUserDefinedShortCircuitingOperator(node As BoundUserDefinedShortCircuitingOperator) As BoundNode Dim leftOperandPlaceholder As BoundRValuePlaceholder = node.LeftOperandPlaceholder PlaceholderReplacementMap.Add(leftOperandPlaceholder, leftOperandPlaceholder.Update(VisitType(leftOperandPlaceholder.Type))) Dim result As BoundNode = MyBase.VisitUserDefinedShortCircuitingOperator(node) PlaceholderReplacementMap.Remove(leftOperandPlaceholder) Return result End Function #End Region End Class End Namespace
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 ElseKeywordRecommenderTests : 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 TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 ElseKeywordRecommenderTests : 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 TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/Core/Portable/Rename/ConflictEngine/RenamedSpansTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// Tracks the text spans that were modified as part of a rename operation /// </summary> internal sealed class RenamedSpansTracker { private readonly Dictionary<DocumentId, List<(TextSpan oldSpan, TextSpan newSpan)>> _documentToModifiedSpansMap; private readonly Dictionary<DocumentId, List<MutableComplexifiedSpan>> _documentToComplexifiedSpansMap; public RenamedSpansTracker() { _documentToComplexifiedSpansMap = new Dictionary<DocumentId, List<MutableComplexifiedSpan>>(); _documentToModifiedSpansMap = new Dictionary<DocumentId, List<(TextSpan oldSpan, TextSpan newSpan)>>(); } internal bool IsDocumentChanged(DocumentId documentId) => _documentToModifiedSpansMap.ContainsKey(documentId) || _documentToComplexifiedSpansMap.ContainsKey(documentId); internal void AddModifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan newSpan) { if (!_documentToModifiedSpansMap.TryGetValue(documentId, out var spans)) { spans = new List<(TextSpan oldSpan, TextSpan newSpan)>(); _documentToModifiedSpansMap[documentId] = spans; } spans.Add((oldSpan, newSpan)); } internal void AddComplexifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan newSpan, List<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans) { if (!_documentToComplexifiedSpansMap.TryGetValue(documentId, out var spans)) { spans = new List<MutableComplexifiedSpan>(); _documentToComplexifiedSpansMap[documentId] = spans; } spans.Add(new MutableComplexifiedSpan() { OriginalSpan = oldSpan, NewSpan = newSpan, ModifiedSubSpans = modifiedSubSpans }); } // Given a position in the old solution, we get back the new adjusted position internal int GetAdjustedPosition(int startingPosition, DocumentId documentId) { var documentReplacementSpans = _documentToModifiedSpansMap.ContainsKey(documentId) ? _documentToModifiedSpansMap[documentId].Where(pair => pair.oldSpan.Start < startingPosition) : SpecializedCollections.EmptyEnumerable<(TextSpan oldSpan, TextSpan newSpan)>(); var adjustedStartingPosition = startingPosition; foreach (var (oldSpan, newSpan) in documentReplacementSpans) { adjustedStartingPosition += newSpan.Length - oldSpan.Length; } var documentComplexifiedSpans = _documentToComplexifiedSpansMap.ContainsKey(documentId) ? _documentToComplexifiedSpansMap[documentId].Where(c => c.OriginalSpan.Start <= startingPosition) : SpecializedCollections.EmptyEnumerable<MutableComplexifiedSpan>(); var appliedTextSpans = new HashSet<TextSpan>(); foreach (var c in documentComplexifiedSpans.Reverse()) { if (startingPosition >= c.OriginalSpan.End && !appliedTextSpans.Any(s => s.Contains(c.OriginalSpan))) { appliedTextSpans.Add(c.OriginalSpan); adjustedStartingPosition += c.NewSpan.Length - c.OriginalSpan.Length; } else { foreach (var (oldSpan, newSpan) in c.ModifiedSubSpans.OrderByDescending(t => t.oldSpan.Start)) { if (!appliedTextSpans.Any(s => s.Contains(oldSpan))) { if (startingPosition == oldSpan.Start) { return startingPosition + newSpan.Start - oldSpan.Start; } else if (startingPosition > oldSpan.Start) { return startingPosition + newSpan.End - oldSpan.End; } } } // if we get here, the starting position passed in is in the middle of our complexified // span at a position that wasn't modified during complexification. } } return adjustedStartingPosition; } /// <summary> /// Information to track deltas of complexified spans /// /// Consider the following example where renaming a->b causes a conflict /// and Goo is an extension method: /// "a.Goo(a)" is rewritten to "NS1.NS2.Goo(NS3.a, NS3.a)" /// /// The OriginalSpan is the span of "a.Goo(a)" /// /// The NewSpan is the span of "NS1.NS2.Goo(NS3.a, NS3.a)" /// /// The ModifiedSubSpans are the pairs of complexified symbols sorted /// according to their order in the original source code span: /// "a", "NS3.a" /// "Goo", "NS1.NS2.Goo" /// "a", "NS3.a" /// /// </summary> private class MutableComplexifiedSpan { public TextSpan OriginalSpan; public TextSpan NewSpan; public List<(TextSpan oldSpan, TextSpan newSpan)> ModifiedSubSpans; } internal void ClearDocuments(IEnumerable<DocumentId> conflictLocationDocumentIds) { foreach (var documentId in conflictLocationDocumentIds) { _documentToModifiedSpansMap.Remove(documentId); _documentToComplexifiedSpansMap.Remove(documentId); } } public IEnumerable<DocumentId> DocumentIds { get { return _documentToModifiedSpansMap.Keys.Concat(_documentToComplexifiedSpansMap.Keys).Distinct(); } } internal async Task<Solution> SimplifyAsync(Solution solution, IEnumerable<DocumentId> documentIds, bool replacementTextValid, AnnotationTable<RenameAnnotation> renameAnnotations, CancellationToken cancellationToken) { foreach (var documentId in documentIds) { if (this.IsDocumentChanged(documentId)) { var document = solution.GetDocument(documentId); if (replacementTextValid) { document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); } // Simplification may have removed escaping and formatted whitespace. We need to update // our list of modified spans accordingly if (_documentToModifiedSpansMap.TryGetValue(documentId, out var modifiedSpans)) { modifiedSpans.Clear(); } if (_documentToComplexifiedSpansMap.TryGetValue(documentId, out var complexifiedSpans)) { complexifiedSpans.Clear(); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // First, get all the complexified statements var nodeAnnotations = renameAnnotations.GetAnnotatedNodesAndTokens<RenameNodeSimplificationAnnotation>(root) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameNodeSimplificationAnnotation>(x).First(), (SyntaxNode)x)); var modifiedTokensInComplexifiedStatements = new HashSet<SyntaxToken>(); foreach (var annotationAndNode in nodeAnnotations) { var oldSpan = annotationAndNode.Item1.OriginalTextSpan; var node = annotationAndNode.Item2; var annotationAndTokens2 = renameAnnotations.GetAnnotatedNodesAndTokens<RenameTokenSimplificationAnnotation>(node) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameTokenSimplificationAnnotation>(x).First(), (SyntaxToken)x)); var modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>(); foreach (var annotationAndToken in annotationAndTokens2) { modifiedTokensInComplexifiedStatements.Add(annotationAndToken.Item2); modifiedSubSpans.Add((annotationAndToken.Item1.OriginalTextSpan, annotationAndToken.Item2.Span)); } AddComplexifiedSpan(documentId, oldSpan, node.Span, modifiedSubSpans); } // Now process the rest of the renamed spans var annotationAndTokens = renameAnnotations.GetAnnotatedNodesAndTokens<RenameTokenSimplificationAnnotation>(root) .Where(x => !modifiedTokensInComplexifiedStatements.Contains((SyntaxToken)x)) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameTokenSimplificationAnnotation>(x).First(), (SyntaxToken)x)); foreach (var annotationAndToken in annotationAndTokens) { AddModifiedSpan(documentId, annotationAndToken.Item1.OriginalTextSpan, annotationAndToken.Item2.Span); } var annotationAndTrivias = renameAnnotations.GetAnnotatedTrivia<RenameTokenSimplificationAnnotation>(root) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameTokenSimplificationAnnotation>(x).First(), x)); foreach (var annotationAndTrivia in annotationAndTrivias) { AddModifiedSpan(documentId, annotationAndTrivia.Item1.OriginalTextSpan, annotationAndTrivia.Item2.Span); } solution = document.Project.Solution; } } return solution; } public ImmutableDictionary<DocumentId, ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)>> GetDocumentToModifiedSpansMap() { var builder = ImmutableDictionary.CreateBuilder<DocumentId, ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)>>(); foreach (var (docId, spans) in _documentToModifiedSpansMap) builder.Add(docId, spans.ToImmutableArray()); return builder.ToImmutable(); } public ImmutableDictionary<DocumentId, ImmutableArray<ComplexifiedSpan>> GetDocumentToComplexifiedSpansMap() { var builder = ImmutableDictionary.CreateBuilder<DocumentId, ImmutableArray<ComplexifiedSpan>>(); foreach (var (docId, spans) in _documentToComplexifiedSpansMap) { builder.Add(docId, spans.SelectAsArray( s => new ComplexifiedSpan(s.OriginalSpan, s.NewSpan, s.ModifiedSubSpans.ToImmutableArray()))); } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// Tracks the text spans that were modified as part of a rename operation /// </summary> internal sealed class RenamedSpansTracker { private readonly Dictionary<DocumentId, List<(TextSpan oldSpan, TextSpan newSpan)>> _documentToModifiedSpansMap; private readonly Dictionary<DocumentId, List<MutableComplexifiedSpan>> _documentToComplexifiedSpansMap; public RenamedSpansTracker() { _documentToComplexifiedSpansMap = new Dictionary<DocumentId, List<MutableComplexifiedSpan>>(); _documentToModifiedSpansMap = new Dictionary<DocumentId, List<(TextSpan oldSpan, TextSpan newSpan)>>(); } internal bool IsDocumentChanged(DocumentId documentId) => _documentToModifiedSpansMap.ContainsKey(documentId) || _documentToComplexifiedSpansMap.ContainsKey(documentId); internal void AddModifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan newSpan) { if (!_documentToModifiedSpansMap.TryGetValue(documentId, out var spans)) { spans = new List<(TextSpan oldSpan, TextSpan newSpan)>(); _documentToModifiedSpansMap[documentId] = spans; } spans.Add((oldSpan, newSpan)); } internal void AddComplexifiedSpan(DocumentId documentId, TextSpan oldSpan, TextSpan newSpan, List<(TextSpan oldSpan, TextSpan newSpan)> modifiedSubSpans) { if (!_documentToComplexifiedSpansMap.TryGetValue(documentId, out var spans)) { spans = new List<MutableComplexifiedSpan>(); _documentToComplexifiedSpansMap[documentId] = spans; } spans.Add(new MutableComplexifiedSpan() { OriginalSpan = oldSpan, NewSpan = newSpan, ModifiedSubSpans = modifiedSubSpans }); } // Given a position in the old solution, we get back the new adjusted position internal int GetAdjustedPosition(int startingPosition, DocumentId documentId) { var documentReplacementSpans = _documentToModifiedSpansMap.ContainsKey(documentId) ? _documentToModifiedSpansMap[documentId].Where(pair => pair.oldSpan.Start < startingPosition) : SpecializedCollections.EmptyEnumerable<(TextSpan oldSpan, TextSpan newSpan)>(); var adjustedStartingPosition = startingPosition; foreach (var (oldSpan, newSpan) in documentReplacementSpans) { adjustedStartingPosition += newSpan.Length - oldSpan.Length; } var documentComplexifiedSpans = _documentToComplexifiedSpansMap.ContainsKey(documentId) ? _documentToComplexifiedSpansMap[documentId].Where(c => c.OriginalSpan.Start <= startingPosition) : SpecializedCollections.EmptyEnumerable<MutableComplexifiedSpan>(); var appliedTextSpans = new HashSet<TextSpan>(); foreach (var c in documentComplexifiedSpans.Reverse()) { if (startingPosition >= c.OriginalSpan.End && !appliedTextSpans.Any(s => s.Contains(c.OriginalSpan))) { appliedTextSpans.Add(c.OriginalSpan); adjustedStartingPosition += c.NewSpan.Length - c.OriginalSpan.Length; } else { foreach (var (oldSpan, newSpan) in c.ModifiedSubSpans.OrderByDescending(t => t.oldSpan.Start)) { if (!appliedTextSpans.Any(s => s.Contains(oldSpan))) { if (startingPosition == oldSpan.Start) { return startingPosition + newSpan.Start - oldSpan.Start; } else if (startingPosition > oldSpan.Start) { return startingPosition + newSpan.End - oldSpan.End; } } } // if we get here, the starting position passed in is in the middle of our complexified // span at a position that wasn't modified during complexification. } } return adjustedStartingPosition; } /// <summary> /// Information to track deltas of complexified spans /// /// Consider the following example where renaming a->b causes a conflict /// and Goo is an extension method: /// "a.Goo(a)" is rewritten to "NS1.NS2.Goo(NS3.a, NS3.a)" /// /// The OriginalSpan is the span of "a.Goo(a)" /// /// The NewSpan is the span of "NS1.NS2.Goo(NS3.a, NS3.a)" /// /// The ModifiedSubSpans are the pairs of complexified symbols sorted /// according to their order in the original source code span: /// "a", "NS3.a" /// "Goo", "NS1.NS2.Goo" /// "a", "NS3.a" /// /// </summary> private class MutableComplexifiedSpan { public TextSpan OriginalSpan; public TextSpan NewSpan; public List<(TextSpan oldSpan, TextSpan newSpan)> ModifiedSubSpans; } internal void ClearDocuments(IEnumerable<DocumentId> conflictLocationDocumentIds) { foreach (var documentId in conflictLocationDocumentIds) { _documentToModifiedSpansMap.Remove(documentId); _documentToComplexifiedSpansMap.Remove(documentId); } } public IEnumerable<DocumentId> DocumentIds { get { return _documentToModifiedSpansMap.Keys.Concat(_documentToComplexifiedSpansMap.Keys).Distinct(); } } internal async Task<Solution> SimplifyAsync(Solution solution, IEnumerable<DocumentId> documentIds, bool replacementTextValid, AnnotationTable<RenameAnnotation> renameAnnotations, CancellationToken cancellationToken) { foreach (var documentId in documentIds) { if (this.IsDocumentChanged(documentId)) { var document = solution.GetDocument(documentId); if (replacementTextValid) { document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); } // Simplification may have removed escaping and formatted whitespace. We need to update // our list of modified spans accordingly if (_documentToModifiedSpansMap.TryGetValue(documentId, out var modifiedSpans)) { modifiedSpans.Clear(); } if (_documentToComplexifiedSpansMap.TryGetValue(documentId, out var complexifiedSpans)) { complexifiedSpans.Clear(); } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // First, get all the complexified statements var nodeAnnotations = renameAnnotations.GetAnnotatedNodesAndTokens<RenameNodeSimplificationAnnotation>(root) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameNodeSimplificationAnnotation>(x).First(), (SyntaxNode)x)); var modifiedTokensInComplexifiedStatements = new HashSet<SyntaxToken>(); foreach (var annotationAndNode in nodeAnnotations) { var oldSpan = annotationAndNode.Item1.OriginalTextSpan; var node = annotationAndNode.Item2; var annotationAndTokens2 = renameAnnotations.GetAnnotatedNodesAndTokens<RenameTokenSimplificationAnnotation>(node) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameTokenSimplificationAnnotation>(x).First(), (SyntaxToken)x)); var modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>(); foreach (var annotationAndToken in annotationAndTokens2) { modifiedTokensInComplexifiedStatements.Add(annotationAndToken.Item2); modifiedSubSpans.Add((annotationAndToken.Item1.OriginalTextSpan, annotationAndToken.Item2.Span)); } AddComplexifiedSpan(documentId, oldSpan, node.Span, modifiedSubSpans); } // Now process the rest of the renamed spans var annotationAndTokens = renameAnnotations.GetAnnotatedNodesAndTokens<RenameTokenSimplificationAnnotation>(root) .Where(x => !modifiedTokensInComplexifiedStatements.Contains((SyntaxToken)x)) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameTokenSimplificationAnnotation>(x).First(), (SyntaxToken)x)); foreach (var annotationAndToken in annotationAndTokens) { AddModifiedSpan(documentId, annotationAndToken.Item1.OriginalTextSpan, annotationAndToken.Item2.Span); } var annotationAndTrivias = renameAnnotations.GetAnnotatedTrivia<RenameTokenSimplificationAnnotation>(root) .Select(x => Tuple.Create(renameAnnotations.GetAnnotations<RenameTokenSimplificationAnnotation>(x).First(), x)); foreach (var annotationAndTrivia in annotationAndTrivias) { AddModifiedSpan(documentId, annotationAndTrivia.Item1.OriginalTextSpan, annotationAndTrivia.Item2.Span); } solution = document.Project.Solution; } } return solution; } public ImmutableDictionary<DocumentId, ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)>> GetDocumentToModifiedSpansMap() { var builder = ImmutableDictionary.CreateBuilder<DocumentId, ImmutableArray<(TextSpan oldSpan, TextSpan newSpan)>>(); foreach (var (docId, spans) in _documentToModifiedSpansMap) builder.Add(docId, spans.ToImmutableArray()); return builder.ToImmutable(); } public ImmutableDictionary<DocumentId, ImmutableArray<ComplexifiedSpan>> GetDocumentToComplexifiedSpansMap() { var builder = ImmutableDictionary.CreateBuilder<DocumentId, ImmutableArray<ComplexifiedSpan>>(); foreach (var (docId, spans) in _documentToComplexifiedSpansMap) { builder.Add(docId, spans.SelectAsArray( s => new ComplexifiedSpan(s.OriginalSpan, s.NewSpan, s.ModifiedSubSpans.ToImmutableArray()))); } return builder.ToImmutable(); } } }
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Compilers/RealParserTests/RealParserTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <ProjectGuid>{315BB5EF-73A8-44DD-A6F8-C07680D1E4FF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>RealParserTests</RootNamespace> <AssemblyName>RealParserTests</AssemblyName> <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath> <IsCodedUITest>False</IsCodedUITest> <TestProjectType>UnitTest</TestProjectType> <IsTestProject>true</IsTestProject> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Numerics" /> </ItemGroup> <Choose> <When Condition="('$(VisualStudioVersion)' == '10.0' OR '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'"> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> </ItemGroup> </When> <Otherwise> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" /> </ItemGroup> </Otherwise> </Choose> <ItemGroup> <Compile Include="..\Core\Portable\RealParser.cs"> <Link>RealParser.cs</Link> </Compile> <Compile Include="RandomRealParserTests.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CLibraryShim\CLibraryShim.vcxproj"> <Project>{d8c0bd38-f641-4d8e-a2e0-8f89f30531b2}</Project> <Name>CLibraryShim</Name> </ProjectReference> </ItemGroup> <Choose> <When Condition="'$(VisualStudioVersion)' == '10.0' AND '$(IsCodedUITest)' == 'True'"> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> </ItemGroup> </When> </Choose> <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <ProjectGuid>{315BB5EF-73A8-44DD-A6F8-C07680D1E4FF}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>RealParserTests</RootNamespace> <AssemblyName>RealParserTests</AssemblyName> <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath> <IsCodedUITest>False</IsCodedUITest> <TestProjectType>UnitTest</TestProjectType> <IsTestProject>true</IsTestProject> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Numerics" /> </ItemGroup> <Choose> <When Condition="('$(VisualStudioVersion)' == '10.0' OR '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'"> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> </ItemGroup> </When> <Otherwise> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" /> </ItemGroup> </Otherwise> </Choose> <ItemGroup> <Compile Include="..\Core\Portable\RealParser.cs"> <Link>RealParser.cs</Link> </Compile> <Compile Include="RandomRealParserTests.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CLibraryShim\CLibraryShim.vcxproj"> <Project>{d8c0bd38-f641-4d8e-a2e0-8f89f30531b2}</Project> <Name>CLibraryShim</Name> </ProjectReference> </ItemGroup> <Choose> <When Condition="'$(VisualStudioVersion)' == '10.0' AND '$(IsCodedUITest)' == 'True'"> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> <Private>False</Private> </Reference> </ItemGroup> </When> </Choose> <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,480
[main] Update dependencies from dotnet/arcade
This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
dotnet-maestro[bot]
"2021-09-17T12:12:26Z"
"2021-09-24T00:35:48Z"
b5a254fe5503b051d63665618025d2d6f22cf0f0
633346af571d640eeacb2e2fc724f5d25ed20faa
[main] Update dependencies from dotnet/arcade. This pull request updates the following dependencies [marker]: <> (Begin:7e4fe80a-482b-4a41-5b66-08d8d8feb47e) ## From https://github.com/dotnet/arcade - **Subscription**: 7e4fe80a-482b-4a41-5b66-08d8d8feb47e - **Build**: 20210922.4 - **Date Produced**: September 22, 2021 3:00:12 PM UTC - **Commit**: 8b2142306838fb8e155e12c1d8a9f59c9c4cd73f - **Branch**: refs/heads/main [DependencyUpdate]: <> (Begin) - **Updates**: - **Microsoft.DotNet.Arcade.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] - **Microsoft.DotNet.Helix.Sdk**: [from 7.0.0-beta.21463.4 to 7.0.0-beta.21472.4][1] [1]: https://github.com/dotnet/arcade/compare/4b7c80f...8b21423 [DependencyUpdate]: <> (End) [marker]: <> (End:7e4fe80a-482b-4a41-5b66-08d8d8feb47e)
./src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.cs.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="cs" original="../VBWorkspaceResources.resx"> <body> <trans-unit id="Namespace_can_not_be_added_in_this_destination"> <source>Namespace can not be added in this destination.</source> <target state="translated">Obor názvů nejde přidat do tohoto cílového umístění.</target> <note /> </trans-unit> <trans-unit id="Only_attributes_expressions_or_statements_can_be_made_explicit"> <source>Only attributes, expressions or statements can be made explicit</source> <target state="translated">Jako explicitní jde nastavit jenom atributy, výrazy nebo příkazy.</target> <note /> </trans-unit> <trans-unit id="Remove_and_Sort_Imports"> <source>R&amp;emove and Sort Imports</source> <target state="translated">&amp;Odebrat a seřadit importy</target> <note /> </trans-unit> <trans-unit id="Sort_Imports"> <source>&amp;Sort Imports</source> <target state="translated">&amp;Seřadit importy</target> <note /> </trans-unit> <trans-unit id="event_"> <source>&lt;event&gt;</source> <target state="translated">&lt;událost&gt;</target> <note /> </trans-unit> <trans-unit id="handler"> <source>&lt;handler&gt;</source> <target state="translated">&lt;obslužná_rutina&gt;</target> <note /> </trans-unit> <trans-unit id="The_expression_to_be_evaluated_and_converted"> <source>The expression to be evaluated and converted.</source> <target state="translated">Výraz k vyhodnocení a převedení</target> <note /> </trans-unit> <trans-unit id="The_name_of_the_data_type_to_which_the_value_of_expression_will_be_converted"> <source>The name of the data type to which the value of expression will be converted.</source> <target state="translated">Název datového typu, na který se převede hodnota výrazu</target> <note /> </trans-unit> <trans-unit id="expression"> <source>&lt;expression&gt;</source> <target state="translated">&lt;výraz&gt;</target> <note /> </trans-unit> <trans-unit id="typeName"> <source>&lt;typeName&gt;</source> <target state="translated">&lt;typeName&gt;</target> <note /> </trans-unit> <trans-unit id="Associates_an_event_with_an_event_handler_delegate_or_lambda_expression_at_run_time"> <source>Associates an event with an event handler, delegate or lambda expression at run time.</source> <target state="translated">Za běhu přidruží událost k obslužné rutině události, delegátu nebo lambda výrazu.</target> <note /> </trans-unit> <trans-unit id="The_event_to_associate_an_event_handler_delegate_or_lambda_expression_with"> <source>The event to associate an event handler, delegate or lambda expression with.</source> <target state="translated">Událost, ke které se má přidružit obslužná rutina události, delegát nebo lambda výraz</target> <note /> </trans-unit> <trans-unit id="The_event_handler_to_associate_with_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate_lambdaExpression"> <source>The event handler to associate with the event. This may take the form of { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; | &lt;lambdaExpression&gt; }.</source> <target state="translated">Obslužná rutina události, která se má přidružit k události. Může být ve tvaru { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; | &lt;lambdaExpression&gt; }.</target> <note /> </trans-unit> <trans-unit id="If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing"> <source>If &lt;expression&gt; evaluates to a reference or Nullable value that is not Nothing, the function returns that value. Otherwise, it calculates and returns &lt;expressionIfNothing&gt;.</source> <target state="translated">Pokud se &lt;výraz&gt; vyhodnotí jako odkaz nebo hodnota s možnou hodnotou null, která není Nothing, funkce vrátí tuto hodnotu. Jinak vypočítá a vrátí &lt;výraz_pokud_Nothing&gt;.</target> <note /> </trans-unit> <trans-unit id="Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing"> <source>Returned if it evaluates to a reference or nullable type that is not Nothing.</source> <target state="translated">Vrátí se, pokud se vyhodnotí na odkaz nebo typ s možnou hodnotou null, který není Nothing.</target> <note /> </trans-unit> <trans-unit id="Evaluated_and_returned_if_expression_evaluates_to_Nothing"> <source>Evaluated and returned if &lt;expression&gt; evaluates to Nothing.</source> <target state="translated">Vyhodnotí se a vrátí se, pokud se &lt;výraz&gt; vyhodnotí jako Nothing.</target> <note /> </trans-unit> <trans-unit id="expressionIfNothing"> <source>&lt;expressionIfNothing&gt;</source> <target state="translated">&lt;expressionIfNothing&gt;</target> <note /> </trans-unit> <trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type"> <source>Returns the result of explicitly converting an expression to a specified data type.</source> <target state="translated">Vrací výsledek explicitně převedeného výrazu na zadaný datový typ, objekt, strukturu, třídu nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type"> <source>Introduces a type conversion operation similar to CType. The difference is that CType succeeds as long as there is a valid conversion, whereas DirectCast requires that one type inherit from or implement the other type.</source> <target state="translated">Zavádí operaci převodu typu podobnou k CType. Rozdíl je v tom, že CType uspěje, pokud existuje platný převod, zatímco DirectCast vyžaduje, aby jeden typ dědil z dalšího typu nebo implementoval další typ.</target> <note /> </trans-unit> <trans-unit id="The_type_name_to_return_a_System_Type_object_for"> <source>The type name to return a System.Type object for.</source> <target state="translated">Název typu, pro který se má vrátit objekt System.Type</target> <note /> </trans-unit> <trans-unit id="Returns_a_System_Type_object_for_the_specified_type_name"> <source>Returns a System.Type object for the specified type name.</source> <target state="translated">Vrátí objekt System.Type pro zadaný název typu.</target> <note /> </trans-unit> <trans-unit id="The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned"> <source>The XML namespace prefix to return a System.Xml.Linq.XNamespace object for. If this is omitted, the object for the default XML namespace is returned.</source> <target state="translated">Předpona názvového prostoru XML, pro kterou se má vracet objekt System.Xml.Linq.XNamespace. Pokud není určená, vrátí se objekt pro výchozí názvový prostor XML.</target> <note /> </trans-unit> <trans-unit id="xmlNamespacePrefix"> <source>&lt;xmlNamespacePrefix&gt;</source> <target state="translated">&lt;předpona_názvového_prostoru_XML&gt;</target> <note /> </trans-unit> <trans-unit id="Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix"> <source>Returns the System.Xml.Linq.XNamespace object corresponding to the specified XML namespace prefix.</source> <target state="translated">Vrátí objekt System.Xml.XLinq.XNamespace odpovídající zadané předponě názvového prostoru XML.</target> <note /> </trans-unit> <trans-unit id="Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string"> <source>Replaces a specified number of characters in a String variable with characters from another string.</source> <target state="translated">Nahradí určitý počet znaků v proměnné typu Řetězec znaky z jiného řetězce.</target> <note /> </trans-unit> <trans-unit id="The_name_of_the_string_variable_to_modify"> <source>The name of the string variable to modify.</source> <target state="translated">Název proměnné řetězce k úpravě</target> <note /> </trans-unit> <trans-unit id="The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins"> <source>The one-based character position in the string where the replacement of text begins.</source> <target state="translated">Pozice znaku se základem 1 v řetězci, kde začne nahrazování textu</target> <note /> </trans-unit> <trans-unit id="The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used"> <source>The number of characters to replace. If omitted, the length of &lt;stringExpression&gt; is used.</source> <target state="translated">Počet znaků k nahrazení. Pokud není určený, použije se délka &lt;výraz_řetězce&gt;.</target> <note /> </trans-unit> <trans-unit id="stringName"> <source>&lt;stringName&gt;</source> <target state="translated">&lt;stringName&gt;</target> <note /> </trans-unit> <trans-unit id="startIndex"> <source>&lt;startIndex&gt;</source> <target state="translated">&lt;startIndex&gt;</target> <note /> </trans-unit> <trans-unit id="length"> <source>&lt;length&gt;</source> <target state="translated">&lt;délka&gt;</target> <note /> </trans-unit> <trans-unit id="stringExpression"> <source>&lt;stringExpression&gt;</source> <target state="translated">&lt;výraz_řetězce&gt;</target> <note /> </trans-unit> <trans-unit id="Converts_an_expression_to_the_0_data_type"> <source>Converts an expression to the {0} data type.</source> <target state="translated">Převede výraz na datový typ {0}.</target> <note /> </trans-unit> <trans-unit id="Removes_the_association_between_an_event_and_an_event_handler_or_delegate_at_run_time"> <source>Removes the association between an event and an event handler or delegate at run time.</source> <target state="translated">Za běhu odebere přidružení mezi událostí a obslužnou rutinou události nebo delegátem.</target> <note /> </trans-unit> <trans-unit id="The_event_to_disassociate_an_event_handler_or_delegate_from"> <source>The event to disassociate an event handler or delegate from.</source> <target state="translated">Událost, u které se má zrušit přidružení obslužné rutiny události nebo delegáta</target> <note /> </trans-unit> <trans-unit id="The_event_handler_to_disassociate_from_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate"> <source>The event handler to disassociate from the event. This may take the form of { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; }.</source> <target state="translated">Obslužná rutina události, jejíž přidružení k události se má zrušit. Může být ve tvaru { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; }.</target> <note /> </trans-unit> <trans-unit id="If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse"> <source>If &lt;condition&gt; returns True, the function calculates and returns &lt;expressionIfTrue&gt;. Otherwise, it returns &lt;expressionIfFalse&gt;.</source> <target state="translated">Pokud &lt;condition&gt; vrátí True, funkce vypočítá a vrátí &lt;expressionIfTrue&gt;. Jinak vrátí &lt;expressionIfFalse&gt;.</target> <note /> </trans-unit> <trans-unit id="The_expression_to_evaluate"> <source>The expression to evaluate.</source> <target state="translated">Výraz k vyhodnocení</target> <note /> </trans-unit> <trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_True"> <source>Evaluated and returned if &lt;condition&gt; evaluates to True.</source> <target state="translated">Vyhodnotí se a vrátí se, pokud se &lt;podmínka&gt; vyhodnotí jako True.</target> <note /> </trans-unit> <trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_False"> <source>Evaluated and returned if &lt;condition&gt; evaluates to False.</source> <target state="translated">Vyhodnotí se a vrátí se, pokud se &lt;podmínka&gt; vyhodnotí jako False.</target> <note /> </trans-unit> <trans-unit id="condition"> <source>&lt;condition&gt;</source> <target state="translated">&lt;podmínka&gt;</target> <note /> </trans-unit> <trans-unit id="expressionIfTrue"> <source>&lt;expressionIfTrue&gt;</source> <target state="translated">&lt;expressionIfTrue&gt;</target> <note /> </trans-unit> <trans-unit id="expressionIfFalse"> <source>&lt;expressionIfFalse&gt;</source> <target state="translated">&lt;expressionIfFalse&gt;</target> <note /> </trans-unit> <trans-unit id="Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for"> <source>Introduces a type conversion operation that does not throw an exception. If an attempted conversion fails, TryCast returns Nothing, which your program can test for.</source> <target state="translated">Zavádí operaci převodu typu, která nevyvolá výjimku. Pokud se pokus o převod nezdaří, TryCast vrací hodnotu Nothing, kterou může váš program testovat.</target> <note /> </trans-unit> <trans-unit id="Node_does_not_descend_from_root"> <source>Node does not descend from root.</source> <target state="translated">Uzel nesestupuje z kořene.</target> <note /> </trans-unit> <trans-unit id="Node_not_in_parent_s_child_list"> <source>Node not in parent's child list</source> <target state="translated">Uzel není v seznamu podřízených položek u nadřazené položky.</target> <note /> </trans-unit> <trans-unit id="Trivia_is_not_associated_with_token"> <source>Trivia is not associated with token</source> <target state="translated">Triviální prvek není přidružený k tokenu.</target> <note /> </trans-unit> <trans-unit id="typeOrMember"> <source>&lt;typeOrMember&gt;</source> <target state="translated">&lt;typeOrMember&gt;</target> <note /> </trans-unit> <trans-unit id="The_type_of_member_to_return_the_name_of"> <source>The type of member to return the name of.</source> <target state="translated">Typ člena, jehož název se má vrátit</target> <note /> </trans-unit> <trans-unit id="Produces_a_string_for_the_name_of_the_specified_type_or_member"> <source>Produces a string for the name of the specified type or member.</source> <target state="translated">Vytvoří řetězec názvu určeného typu nebo člena.</target> <note /> </trans-unit> <trans-unit id="result"> <source>&lt;result&gt;</source> <target state="translated">&lt;výsledek&gt;</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="cs" original="../VBWorkspaceResources.resx"> <body> <trans-unit id="Namespace_can_not_be_added_in_this_destination"> <source>Namespace can not be added in this destination.</source> <target state="translated">Obor názvů nejde přidat do tohoto cílového umístění.</target> <note /> </trans-unit> <trans-unit id="Only_attributes_expressions_or_statements_can_be_made_explicit"> <source>Only attributes, expressions or statements can be made explicit</source> <target state="translated">Jako explicitní jde nastavit jenom atributy, výrazy nebo příkazy.</target> <note /> </trans-unit> <trans-unit id="Remove_and_Sort_Imports"> <source>R&amp;emove and Sort Imports</source> <target state="translated">&amp;Odebrat a seřadit importy</target> <note /> </trans-unit> <trans-unit id="Sort_Imports"> <source>&amp;Sort Imports</source> <target state="translated">&amp;Seřadit importy</target> <note /> </trans-unit> <trans-unit id="event_"> <source>&lt;event&gt;</source> <target state="translated">&lt;událost&gt;</target> <note /> </trans-unit> <trans-unit id="handler"> <source>&lt;handler&gt;</source> <target state="translated">&lt;obslužná_rutina&gt;</target> <note /> </trans-unit> <trans-unit id="The_expression_to_be_evaluated_and_converted"> <source>The expression to be evaluated and converted.</source> <target state="translated">Výraz k vyhodnocení a převedení</target> <note /> </trans-unit> <trans-unit id="The_name_of_the_data_type_to_which_the_value_of_expression_will_be_converted"> <source>The name of the data type to which the value of expression will be converted.</source> <target state="translated">Název datového typu, na který se převede hodnota výrazu</target> <note /> </trans-unit> <trans-unit id="expression"> <source>&lt;expression&gt;</source> <target state="translated">&lt;výraz&gt;</target> <note /> </trans-unit> <trans-unit id="typeName"> <source>&lt;typeName&gt;</source> <target state="translated">&lt;typeName&gt;</target> <note /> </trans-unit> <trans-unit id="Associates_an_event_with_an_event_handler_delegate_or_lambda_expression_at_run_time"> <source>Associates an event with an event handler, delegate or lambda expression at run time.</source> <target state="translated">Za běhu přidruží událost k obslužné rutině události, delegátu nebo lambda výrazu.</target> <note /> </trans-unit> <trans-unit id="The_event_to_associate_an_event_handler_delegate_or_lambda_expression_with"> <source>The event to associate an event handler, delegate or lambda expression with.</source> <target state="translated">Událost, ke které se má přidružit obslužná rutina události, delegát nebo lambda výraz</target> <note /> </trans-unit> <trans-unit id="The_event_handler_to_associate_with_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate_lambdaExpression"> <source>The event handler to associate with the event. This may take the form of { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; | &lt;lambdaExpression&gt; }.</source> <target state="translated">Obslužná rutina události, která se má přidružit k události. Může být ve tvaru { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; | &lt;lambdaExpression&gt; }.</target> <note /> </trans-unit> <trans-unit id="If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing"> <source>If &lt;expression&gt; evaluates to a reference or Nullable value that is not Nothing, the function returns that value. Otherwise, it calculates and returns &lt;expressionIfNothing&gt;.</source> <target state="translated">Pokud se &lt;výraz&gt; vyhodnotí jako odkaz nebo hodnota s možnou hodnotou null, která není Nothing, funkce vrátí tuto hodnotu. Jinak vypočítá a vrátí &lt;výraz_pokud_Nothing&gt;.</target> <note /> </trans-unit> <trans-unit id="Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing"> <source>Returned if it evaluates to a reference or nullable type that is not Nothing.</source> <target state="translated">Vrátí se, pokud se vyhodnotí na odkaz nebo typ s možnou hodnotou null, který není Nothing.</target> <note /> </trans-unit> <trans-unit id="Evaluated_and_returned_if_expression_evaluates_to_Nothing"> <source>Evaluated and returned if &lt;expression&gt; evaluates to Nothing.</source> <target state="translated">Vyhodnotí se a vrátí se, pokud se &lt;výraz&gt; vyhodnotí jako Nothing.</target> <note /> </trans-unit> <trans-unit id="expressionIfNothing"> <source>&lt;expressionIfNothing&gt;</source> <target state="translated">&lt;expressionIfNothing&gt;</target> <note /> </trans-unit> <trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type"> <source>Returns the result of explicitly converting an expression to a specified data type.</source> <target state="translated">Vrací výsledek explicitně převedeného výrazu na zadaný datový typ, objekt, strukturu, třídu nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type"> <source>Introduces a type conversion operation similar to CType. The difference is that CType succeeds as long as there is a valid conversion, whereas DirectCast requires that one type inherit from or implement the other type.</source> <target state="translated">Zavádí operaci převodu typu podobnou k CType. Rozdíl je v tom, že CType uspěje, pokud existuje platný převod, zatímco DirectCast vyžaduje, aby jeden typ dědil z dalšího typu nebo implementoval další typ.</target> <note /> </trans-unit> <trans-unit id="The_type_name_to_return_a_System_Type_object_for"> <source>The type name to return a System.Type object for.</source> <target state="translated">Název typu, pro který se má vrátit objekt System.Type</target> <note /> </trans-unit> <trans-unit id="Returns_a_System_Type_object_for_the_specified_type_name"> <source>Returns a System.Type object for the specified type name.</source> <target state="translated">Vrátí objekt System.Type pro zadaný název typu.</target> <note /> </trans-unit> <trans-unit id="The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned"> <source>The XML namespace prefix to return a System.Xml.Linq.XNamespace object for. If this is omitted, the object for the default XML namespace is returned.</source> <target state="translated">Předpona názvového prostoru XML, pro kterou se má vracet objekt System.Xml.Linq.XNamespace. Pokud není určená, vrátí se objekt pro výchozí názvový prostor XML.</target> <note /> </trans-unit> <trans-unit id="xmlNamespacePrefix"> <source>&lt;xmlNamespacePrefix&gt;</source> <target state="translated">&lt;předpona_názvového_prostoru_XML&gt;</target> <note /> </trans-unit> <trans-unit id="Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix"> <source>Returns the System.Xml.Linq.XNamespace object corresponding to the specified XML namespace prefix.</source> <target state="translated">Vrátí objekt System.Xml.XLinq.XNamespace odpovídající zadané předponě názvového prostoru XML.</target> <note /> </trans-unit> <trans-unit id="Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string"> <source>Replaces a specified number of characters in a String variable with characters from another string.</source> <target state="translated">Nahradí určitý počet znaků v proměnné typu Řetězec znaky z jiného řetězce.</target> <note /> </trans-unit> <trans-unit id="The_name_of_the_string_variable_to_modify"> <source>The name of the string variable to modify.</source> <target state="translated">Název proměnné řetězce k úpravě</target> <note /> </trans-unit> <trans-unit id="The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins"> <source>The one-based character position in the string where the replacement of text begins.</source> <target state="translated">Pozice znaku se základem 1 v řetězci, kde začne nahrazování textu</target> <note /> </trans-unit> <trans-unit id="The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used"> <source>The number of characters to replace. If omitted, the length of &lt;stringExpression&gt; is used.</source> <target state="translated">Počet znaků k nahrazení. Pokud není určený, použije se délka &lt;výraz_řetězce&gt;.</target> <note /> </trans-unit> <trans-unit id="stringName"> <source>&lt;stringName&gt;</source> <target state="translated">&lt;stringName&gt;</target> <note /> </trans-unit> <trans-unit id="startIndex"> <source>&lt;startIndex&gt;</source> <target state="translated">&lt;startIndex&gt;</target> <note /> </trans-unit> <trans-unit id="length"> <source>&lt;length&gt;</source> <target state="translated">&lt;délka&gt;</target> <note /> </trans-unit> <trans-unit id="stringExpression"> <source>&lt;stringExpression&gt;</source> <target state="translated">&lt;výraz_řetězce&gt;</target> <note /> </trans-unit> <trans-unit id="Converts_an_expression_to_the_0_data_type"> <source>Converts an expression to the {0} data type.</source> <target state="translated">Převede výraz na datový typ {0}.</target> <note /> </trans-unit> <trans-unit id="Removes_the_association_between_an_event_and_an_event_handler_or_delegate_at_run_time"> <source>Removes the association between an event and an event handler or delegate at run time.</source> <target state="translated">Za běhu odebere přidružení mezi událostí a obslužnou rutinou události nebo delegátem.</target> <note /> </trans-unit> <trans-unit id="The_event_to_disassociate_an_event_handler_or_delegate_from"> <source>The event to disassociate an event handler or delegate from.</source> <target state="translated">Událost, u které se má zrušit přidružení obslužné rutiny události nebo delegáta</target> <note /> </trans-unit> <trans-unit id="The_event_handler_to_disassociate_from_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate"> <source>The event handler to disassociate from the event. This may take the form of { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; }.</source> <target state="translated">Obslužná rutina události, jejíž přidružení k události se má zrušit. Může být ve tvaru { AddressOf &lt;eventHandler&gt; | &lt;delegate&gt; }.</target> <note /> </trans-unit> <trans-unit id="If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse"> <source>If &lt;condition&gt; returns True, the function calculates and returns &lt;expressionIfTrue&gt;. Otherwise, it returns &lt;expressionIfFalse&gt;.</source> <target state="translated">Pokud &lt;condition&gt; vrátí True, funkce vypočítá a vrátí &lt;expressionIfTrue&gt;. Jinak vrátí &lt;expressionIfFalse&gt;.</target> <note /> </trans-unit> <trans-unit id="The_expression_to_evaluate"> <source>The expression to evaluate.</source> <target state="translated">Výraz k vyhodnocení</target> <note /> </trans-unit> <trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_True"> <source>Evaluated and returned if &lt;condition&gt; evaluates to True.</source> <target state="translated">Vyhodnotí se a vrátí se, pokud se &lt;podmínka&gt; vyhodnotí jako True.</target> <note /> </trans-unit> <trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_False"> <source>Evaluated and returned if &lt;condition&gt; evaluates to False.</source> <target state="translated">Vyhodnotí se a vrátí se, pokud se &lt;podmínka&gt; vyhodnotí jako False.</target> <note /> </trans-unit> <trans-unit id="condition"> <source>&lt;condition&gt;</source> <target state="translated">&lt;podmínka&gt;</target> <note /> </trans-unit> <trans-unit id="expressionIfTrue"> <source>&lt;expressionIfTrue&gt;</source> <target state="translated">&lt;expressionIfTrue&gt;</target> <note /> </trans-unit> <trans-unit id="expressionIfFalse"> <source>&lt;expressionIfFalse&gt;</source> <target state="translated">&lt;expressionIfFalse&gt;</target> <note /> </trans-unit> <trans-unit id="Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for"> <source>Introduces a type conversion operation that does not throw an exception. If an attempted conversion fails, TryCast returns Nothing, which your program can test for.</source> <target state="translated">Zavádí operaci převodu typu, která nevyvolá výjimku. Pokud se pokus o převod nezdaří, TryCast vrací hodnotu Nothing, kterou může váš program testovat.</target> <note /> </trans-unit> <trans-unit id="Node_does_not_descend_from_root"> <source>Node does not descend from root.</source> <target state="translated">Uzel nesestupuje z kořene.</target> <note /> </trans-unit> <trans-unit id="Node_not_in_parent_s_child_list"> <source>Node not in parent's child list</source> <target state="translated">Uzel není v seznamu podřízených položek u nadřazené položky.</target> <note /> </trans-unit> <trans-unit id="Trivia_is_not_associated_with_token"> <source>Trivia is not associated with token</source> <target state="translated">Triviální prvek není přidružený k tokenu.</target> <note /> </trans-unit> <trans-unit id="typeOrMember"> <source>&lt;typeOrMember&gt;</source> <target state="translated">&lt;typeOrMember&gt;</target> <note /> </trans-unit> <trans-unit id="The_type_of_member_to_return_the_name_of"> <source>The type of member to return the name of.</source> <target state="translated">Typ člena, jehož název se má vrátit</target> <note /> </trans-unit> <trans-unit id="Produces_a_string_for_the_name_of_the_specified_type_or_member"> <source>Produces a string for the name of the specified type or member.</source> <target state="translated">Vytvoří řetězec názvu určeného typu nebo člena.</target> <note /> </trans-unit> <trans-unit id="result"> <source>&lt;result&gt;</source> <target state="translated">&lt;výsledek&gt;</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Analyzers/CSharp/Tests/MakeLocalFunctionStatic/MakeLocalFunctionStaticTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.MakeLocalFunctionStatic; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic { public partial class MakeLocalFunctionStaticTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeLocalFunctionStaticTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new MakeLocalFunctionStaticDiagnosticAnalyzer(), GetMakeLocalFunctionStaticCodeFixProvider()); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestAboveCSharp8() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", @"using System; class C { void M() { static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseSimpleUsingStatement)] public async Task TestWithOptionOff() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", new TestParameters( parseOptions: CSharp8ParseOptions, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingIfAlreadyStatic() { await TestMissingAsync( @"using System; class C { void M() { static int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingPriorToCSharp8() { await TestMissingAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingIfCapturesValue() { await TestMissingAsync( @"using System; class C { void M(int i) { int [||]fibonacci(int n) { return i <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingIfCapturesThis() { await TestMissingAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { M(); return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestAsyncFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { async Task<int> [||]fibonacci(int n) { return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2); } } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task<int> fibonacci(int n) { return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterSemicolon(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ int x;{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", @"using System; class C { void M() { int x; static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterOpenBrace(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", @"using System; class C { void M() { static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterLocalFunction(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ bool otherFunction() {{ return true; }}{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", @"using System; class C { void M() { bool otherFunction() { return true; } static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterExpressionBodyLocalFunction(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ bool otherFunction() => true;{leadingTrivia} int [||]fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }}", @"using System; class C { void M() { bool otherFunction() => true; static int fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterComment(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ //Local function comment{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", $@"using System; class C {{ void M() {{ //Local function comment{leadingTrivia} static int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaBeforeComment(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{{leadingTrivia} //Local function comment int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", $@"using System; class C {{ void M() {{{leadingTrivia} //Local function comment static int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(46858, "https://github.com/dotnet/roslyn/issues/46858")] public async Task TestMissingIfAnotherLocalFunctionCalled() { await TestMissingAsync( @"using System; class C { void M() { void [||]A() { B(); } void B() { } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingStaticLocalFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { void [||]A() { B(); } static void B() { } } }", @"using System; using System.Threading.Tasks; class C { void M() { static void A() { B(); } static void B() { } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingNestedLocalFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { void [||]A() { B(); void B() { } } } }", @"using System; using System.Threading.Tasks; class C { void M() { static void A() { B(); void B() { } } } }", parseOptions: CSharp8ParseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.MakeLocalFunctionStatic; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic { public partial class MakeLocalFunctionStaticTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeLocalFunctionStaticTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new MakeLocalFunctionStaticDiagnosticAnalyzer(), GetMakeLocalFunctionStaticCodeFixProvider()); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestAboveCSharp8() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", @"using System; class C { void M() { static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseSimpleUsingStatement)] public async Task TestWithOptionOff() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", new TestParameters( parseOptions: CSharp8ParseOptions, options: Option(CSharpCodeStyleOptions.PreferStaticLocalFunction, CodeStyleOptions2.FalseWithSilentEnforcement))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingIfAlreadyStatic() { await TestMissingAsync( @"using System; class C { void M() { static int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingPriorToCSharp8() { await TestMissingAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingIfCapturesValue() { await TestMissingAsync( @"using System; class C { void M(int i) { int [||]fibonacci(int n) { return i <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMissingIfCapturesThis() { await TestMissingAsync( @"using System; class C { void M() { int [||]fibonacci(int n) { M(); return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestAsyncFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { async Task<int> [||]fibonacci(int n) { return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2); } } }", @"using System; using System.Threading.Tasks; class C { void M() { static async Task<int> fibonacci(int n) { return n <= 1 ? n : await fibonacci(n - 1) + await fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterSemicolon(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ int x;{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", @"using System; class C { void M() { int x; static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterOpenBrace(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", @"using System; class C { void M() { static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterLocalFunction(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ bool otherFunction() {{ return true; }}{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", @"using System; class C { void M() { bool otherFunction() { return true; } static int fibonacci(int n) { return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterExpressionBodyLocalFunction(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ bool otherFunction() => true;{leadingTrivia} int [||]fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }}", @"using System; class C { void M() { bool otherFunction() => true; static int fibonacci(int n) => n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); } }", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("")] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaAfterComment(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{ //Local function comment{leadingTrivia} int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", $@"using System; class C {{ void M() {{ //Local function comment{leadingTrivia} static int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", parseOptions: CSharp8ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [InlineData("\r\n")] [InlineData("\r\n\r\n")] public async Task TestLeadingTriviaBeforeComment(string leadingTrivia) { await TestInRegularAndScriptAsync( $@"using System; class C {{ void M() {{{leadingTrivia} //Local function comment int [||]fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", $@"using System; class C {{ void M() {{{leadingTrivia} //Local function comment static int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} }}", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(46858, "https://github.com/dotnet/roslyn/issues/46858")] public async Task TestMissingIfAnotherLocalFunctionCalled() { await TestMissingAsync( @"using System; class C { void M() { void [||]A() { B(); } void B() { } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingStaticLocalFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { void [||]A() { B(); } static void B() { } } }", @"using System; using System.Threading.Tasks; class C { void M() { static void A() { B(); } static void B() { } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingNestedLocalFunction() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class C { void M() { void [||]A() { B(); void B() { } } } }", @"using System; using System.Threading.Tasks; class C { void M() { static void A() { B(); void B() { } } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(53179, "https://github.com/dotnet/roslyn/issues/53179")] public async Task TestLocalFunctionAsTopLevelStatement() { await TestAsync(@" void [||]A() { }", @" static void A() { }", parseOptions: CSharp8ParseOptions); } } }
1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/EditorFeatures/CSharpTest/MakeLocalFunctionStatic/MakeLocalFunctionStaticRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic { public class MakeLocalFunctionStaticRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MakeLocalFunctionStaticCodeRefactoringProvider(); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerForCSharp7() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfNoCaptures() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStatic() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStaticWithError() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); static int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfCapturesThisParameter() { await TestMissingAsync( @"class C { int x; int N() { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerIfExplicitlyPassedInThisParameter() { await TestInRegularAndScriptAsync( @"class C { int x; int N() { int y; return AddLocal(this); int [||]AddLocal(C c) { return c.x + y; } } }", @"class C { int x; int N() { int y; return AddLocal(this, y); static int [||]AddLocal(C c, int y) { return c.x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerForCSharp8() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", @"class C { int N(int x) { return AddLocal(x); static int AddLocal(int x) { return x + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleVariables() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCalls() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal() + AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y) + AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCallsWithExistingParameters() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestRecursiveCall() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallInArgumentList() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2), AddLocal(3, 4)); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2, x, y), AddLocal(3, 4, x, y), x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithNamedArguments() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2); return AddLocal(b: m, a: m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2, x: x, y: y); return AddLocal(b: m, a: m, x: x, y: y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithDafaultValue() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { string y = ""; var m = AddLocal(1); return AddLocal(b: m); int[||] AddLocal(int a = 0, int b = 0) { return a + b + x + y.Length; } } }", @"class C { int N(int x) { string y = ""; var m = AddLocal(1, x: x, y: y); return AddLocal(b: m, x: x, y: y); static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null) { return a + b + x + y.Length; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestWarningAnnotation() { await TestInRegularAndScriptAsync( @"class C { void N(int x) { Func<int> del = AddLocal; int [||]AddLocal() { return x + 1; } } }", @"class C { void N(int x) { Func<int> del = AddLocal; {|Warning:static int AddLocal(int x) { return x + 1; }|} } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestNonCamelCaseCapture() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int Static = 0; return AddLocal(); int [||]AddLocal() { return Static + 1; } } }", @"class C { int N(int x) { int Static = 0; return AddLocal(Static); static int AddLocal(int @static) { return @static + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(46858, "https://github.com/dotnet/roslyn/issues/46858")] public async Task ShouldNotTriggerIfCallsOtherLocalFunction() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } void B() { } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingStaticLocationFunction() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } static void B() { } } }", @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { B(); return x + 1; } static void B() { } } }", parseOptions: CSharp8ParseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeLocalFunctionStatic { public class MakeLocalFunctionStaticRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MakeLocalFunctionStaticCodeRefactoringProvider(); private static readonly ParseOptions CSharp72ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_2); private static readonly ParseOptions CSharp8ParseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerForCSharp7() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp72ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfNoCaptures() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStatic() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfAlreadyStaticWithError() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); static int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldNotTriggerIfCapturesThisParameter() { await TestMissingAsync( @"class C { int x; int N() { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerIfExplicitlyPassedInThisParameter() { await TestInRegularAndScriptAsync( @"class C { int x; int N() { int y; return AddLocal(this); int [||]AddLocal(C c) { return c.x + y; } } }", @"class C { int x; int N() { int y; return AddLocal(this, y); static int [||]AddLocal(C c, int y) { return c.x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task ShouldTriggerForCSharp8() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { return x + 1; } } }", @"class C { int N(int x) { return AddLocal(x); static int AddLocal(int x) { return x + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleVariables() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCalls() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal() + AddLocal(); int[||] AddLocal() { return x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(x, y) + AddLocal(x, y); static int AddLocal(int x, int y) { return x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestMultipleCallsWithExistingParameters() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestRecursiveCall() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2); return AddLocal(m, m); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, 2, x, y); return AddLocal(m, m, x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallInArgumentList() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2), AddLocal(3, 4)); int[||] AddLocal(int a, int b) { return AddLocal(a, b) + x + y; } } }", @"class C { int N(int x) { int y = 10; return AddLocal(AddLocal(1, 2, x, y), AddLocal(3, 4, x, y), x, y); static int AddLocal(int a, int b, int x, int y) { return AddLocal(a, b, x, y) + x + y; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithNamedArguments() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2); return AddLocal(b: m, a: m); int[||] AddLocal(int a, int b) { return a + b + x + y; } } }", @"class C { int N(int x) { int y = 10; var m = AddLocal(1, b: 2, x: x, y: y); return AddLocal(b: m, a: m, x: x, y: y); static int AddLocal(int a, int b, int x, int y) { return a + b + x + y; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallsWithDafaultValue() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { string y = ""; var m = AddLocal(1); return AddLocal(b: m); int[||] AddLocal(int a = 0, int b = 0) { return a + b + x + y.Length; } } }", @"class C { int N(int x) { string y = ""; var m = AddLocal(1, x: x, y: y); return AddLocal(b: m, x: x, y: y); static int AddLocal(int a = 0, int b = 0, int x = 0, string y = null) { return a + b + x + y.Length; } } }" , parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestWarningAnnotation() { await TestInRegularAndScriptAsync( @"class C { void N(int x) { Func<int> del = AddLocal; int [||]AddLocal() { return x + 1; } } }", @"class C { void N(int x) { Func<int> del = AddLocal; {|Warning:static int AddLocal(int x) { return x + 1; }|} } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestNonCamelCaseCapture() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { int Static = 0; return AddLocal(); int [||]AddLocal() { return Static + 1; } } }", @"class C { int N(int x) { int Static = 0; return AddLocal(Static); static int AddLocal(int @static) { return @static + 1; } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(46858, "https://github.com/dotnet/roslyn/issues/46858")] public async Task ShouldNotTriggerIfCallsOtherLocalFunction() { await TestMissingAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } void B() { } } }", parameters: new TestParameters(parseOptions: CSharp8ParseOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] public async Task TestCallingStaticLocationFunction() { await TestInRegularAndScriptAsync( @"class C { int N(int x) { return AddLocal(); int [||]AddLocal() { B(); return x + 1; } static void B() { } } }", @"class C { int N(int x) { return AddLocal(x); static int [||]AddLocal(int x) { B(); return x + 1; } static void B() { } } }", parseOptions: CSharp8ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeLocalFunctionStatic)] [WorkItem(53179, "https://github.com/dotnet/roslyn/issues/53179")] public async Task TestLocalFunctionAsTopLevelStatement() { await TestAsync(@" int y = 10; return AddLocal(); int[||] AddLocal() { return y; } ", @" int y = 10; return AddLocal(y); static int AddLocal(int y) { return y; } ", parseOptions: CSharp8ParseOptions); } } }
1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Features/CSharp/Portable/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared] internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeLocalFunctionStaticCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(cancellationToken)); foreach (var localFunction in localFunctions) { editor.ReplaceNode( localFunction, (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared] internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeLocalFunctionStaticCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken)); foreach (var localFunction in localFunctions) { editor.ReplaceNode( localFunction, (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static) { } } } }
1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/CSharp/Portable/Binder/WithTypeParametersBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class WithTypeParametersBinder : Binder { internal WithTypeParametersBinder(Binder next) : base(next) { } // TODO: Change this to a data structure that won't allocate enumerators protected abstract MultiDictionary<string, TypeParameterSymbol> TypeParameterMap { get; } // This is only overridden by WithMethodTypeParametersBinder. protected virtual LookupOptions LookupMask { get { return LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember; } } protected bool CanConsiderTypeParameters(LookupOptions options) { return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupMask) != 0) { return; } foreach (var typeParameter in TypeParameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(typeParameter, arity, options, null, diagnose, ref useSiteInfo)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class WithTypeParametersBinder : Binder { internal WithTypeParametersBinder(Binder next) : base(next) { } // TODO: Change this to a data structure that won't allocate enumerators protected abstract MultiDictionary<string, TypeParameterSymbol> TypeParameterMap { get; } // This is only overridden by WithMethodTypeParametersBinder. protected virtual LookupOptions LookupMask { get { return LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember; } } protected bool CanConsiderTypeParameters(LookupOptions options) { return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupMask) != 0) { return; } foreach (var typeParameter in TypeParameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(typeParameter, arity, options, null, diagnose, ref useSiteInfo)); } } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/DkmUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Clr.NativeCompilation; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class DkmUtilities { internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize); // Return the set of managed module instances from the AppDomain. private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain) { if (appDomain.IsUnloaded) { return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>(); } var appDomainId = appDomain.Id; // GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance // which are containers of managed module instances (see GetEmbeddedModules()) // but not managed modules themselves. Since GetModuleInstances() will include the // embedded modules, we can simply ignore DkmClrNcContainerModuleInstances. return runtime.GetModuleInstances(). OfType<DkmClrModuleInstance>(). Where(module => { var moduleAppDomain = module.AppDomain; return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId); }); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks( this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> previousMetadataBlocks) { // Add a dummy data item to the appdomain to add it to the disposal queue when the debugged process is shutting down. // This should prevent from attempts to use the Metadata pointer for dead debugged processes. if (appDomain.GetDataItem<AppDomainLifetimeDataItem>() == null) { appDomain.SetDataItem(DkmDataCreationDisposition.CreateNew, new AppDomainLifetimeDataItem()); } var builder = ArrayBuilder<MetadataBlock>.GetInstance(); IntPtr ptr; uint size; int index = 0; foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain)) { MetadataBlock block; try { ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); block = GetMetadataBlock(previousMetadataBlocks, index, ptr, size); } catch (NotImplementedException e) when (module is DkmClrNcModuleInstance) { // DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14. throw new NotImplementedMetadataException(e); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } Debug.Assert(block.ModuleVersionId == module.Mvid); builder.Add(block); index++; } // Include "intrinsic method" assembly. ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size); builder.Add(GetMetadataBlock(previousMetadataBlocks, index, ptr, size)); return builder.ToImmutableAndFree(); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities) { ArrayBuilder<MetadataBlock>? builder = null; foreach (var missingAssemblyIdentity in missingAssemblyIdentities) { MetadataBlock block; try { uint size; IntPtr ptr; ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size); Debug.Assert(size > 0); block = GetMetadataBlock(ptr, size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } if (builder == null) { builder = ArrayBuilder<MetadataBlock>.GetInstance(); } builder.Add(block); } return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree(); } internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress) { var builder = ArrayBuilder<AssemblyReaders>.GetInstance(); foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain)) { var symReader = module.GetSymReader(); if (symReader == null) { continue; } MetadataReader reader; unsafe { try { uint size; IntPtr ptr; ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); reader = new MetadataReader((byte*)ptr, (int)size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } } builder.Add(new AssemblyReaders(reader, symReader)); } return builder.ToImmutableAndFree(); } private static unsafe MetadataBlock GetMetadataBlock(IntPtr ptr, uint size) { var reader = new MetadataReader((byte*)ptr, (int)size); var moduleDef = reader.GetModuleDefinition(); var moduleVersionId = reader.GetGuid(moduleDef.Mvid); var generationId = reader.GetGuid(moduleDef.GenerationId); return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size); } private static MetadataBlock GetMetadataBlock(ImmutableArray<MetadataBlock> previousMetadataBlocks, int index, IntPtr ptr, uint size) { if (!previousMetadataBlocks.IsDefault && index < previousMetadataBlocks.Length) { var previousBlock = previousMetadataBlocks[index]; if (previousBlock.Pointer == ptr && previousBlock.Size == size) { return previousBlock; } } return GetMetadataBlock(ptr, size); } internal static object? GetSymReader(this DkmClrModuleInstance clrModule) { var module = clrModule.Module; // Null if there are no symbols. if (module == null) { return null; } // Use DkmClrModuleInstance.GetSymUnmanagedReader() // rather than DkmModule.GetSymbolInterface() since the // latter does not handle .NET Native modules. return clrModule.GetSymUnmanagedReader(); } internal static DkmCompiledClrInspectionQuery? ToQueryResult( this CompileResult? compResult, DkmCompilerId languageId, ResultProperties resultProperties, DkmClrRuntimeInstance runtimeInstance) { if (compResult == null) { return null; } Debug.Assert(compResult.Assembly != null); Debug.Assert(compResult.TypeName != null); Debug.Assert(compResult.MethodName != null); ReadOnlyCollection<byte>? customTypeInfo; Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo); return DkmCompiledClrInspectionQuery.Create( runtimeInstance, Binary: new ReadOnlyCollection<byte>(compResult.Assembly), DataContainer: null, LanguageId: languageId, TypeName: compResult.TypeName, MethodName: compResult.MethodName, FormatSpecifiers: compResult.FormatSpecifiers, CompilationFlags: resultProperties.Flags, ResultCategory: resultProperties.Category, Access: resultProperties.AccessType, StorageType: resultProperties.StorageType, TypeModifierFlags: resultProperties.ModifierFlags, CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId)); } internal static DkmClrCustomTypeInfo? ToCustomTypeInfo(this ReadOnlyCollection<byte>? payload, Guid payloadTypeId) { return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload); } internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol? symbol, DkmClrCompilationResultFlags flags, bool isConstant) where TSymbol : class, ISymbolInternal { var category = (symbol != null) ? GetResultCategory(symbol.Kind) : DkmEvaluationResultCategory.Data; var accessType = (symbol != null) ? GetResultAccessType(symbol.DeclaredAccessibility) : DkmEvaluationResultAccessType.None; var storageType = (symbol != null) && symbol.IsStatic ? DkmEvaluationResultStorageType.Static : DkmEvaluationResultStorageType.None; var modifierFlags = DkmEvaluationResultTypeModifierFlags.None; if (isConstant) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant; } else if (symbol is null) { // No change. } else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual; } else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbolInternal)symbol).IsVolatile) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile; } // CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)] // and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any // impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either. return new ResultProperties(flags, category, accessType, storageType, modifierFlags); } private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind) { switch (kind) { case SymbolKind.Method: return DkmEvaluationResultCategory.Method; case SymbolKind.Property: return DkmEvaluationResultCategory.Property; default: return DkmEvaluationResultCategory.Data; } } private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility) { switch (accessibility) { case Accessibility.Public: return DkmEvaluationResultAccessType.Public; case Accessibility.Protected: return DkmEvaluationResultAccessType.Protected; case Accessibility.Private: return DkmEvaluationResultAccessType.Private; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal" case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal" return DkmEvaluationResultAccessType.Internal; case Accessibility.NotApplicable: return DkmEvaluationResultAccessType.None; default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired) { return (flags & desired) == desired; } internal static MetadataContext<TAssemblyContext> GetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { var dataItem = appDomain.GetDataItem<MetadataContextItem<MetadataContext<TAssemblyContext>>>(); return (dataItem == null) ? default : dataItem.MetadataContext; } internal static void SetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain, MetadataContext<TAssemblyContext> context, bool report) where TAssemblyContext : struct { if (report) { var process = appDomain.Process; var message = DkmUserMessage.Create( process.Connection, process, DkmUserMessageOutputKind.UnfilteredOutputWindowMessage, $"EE: AppDomain {appDomain.Id}, blocks {context.MetadataBlocks.Length}, contexts {context.AssemblyContexts.Count}" + Environment.NewLine, MessageBoxFlags.MB_OK, 0); message.Post(); } appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<MetadataContext<TAssemblyContext>>(context)); } internal static void RemoveMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { appDomain.RemoveDataItem<MetadataContextItem<TAssemblyContext>>(); } private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem where TMetadataContext : struct { internal readonly TMetadataContext MetadataContext; internal MetadataContextItem(TMetadataContext metadataContext) { this.MetadataContext = metadataContext; } } private sealed class AppDomainLifetimeDataItem : DkmDataItem { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Clr.NativeCompilation; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal static class DkmUtilities { internal unsafe delegate IntPtr GetMetadataBytesPtrFunction(AssemblyIdentity assemblyIdentity, out uint uSize); // Return the set of managed module instances from the AppDomain. private static IEnumerable<DkmClrModuleInstance> GetModulesInAppDomain(this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain) { if (appDomain.IsUnloaded) { return SpecializedCollections.EmptyEnumerable<DkmClrModuleInstance>(); } var appDomainId = appDomain.Id; // GetModuleInstances() may include instances of DkmClrNcContainerModuleInstance // which are containers of managed module instances (see GetEmbeddedModules()) // but not managed modules themselves. Since GetModuleInstances() will include the // embedded modules, we can simply ignore DkmClrNcContainerModuleInstances. return runtime.GetModuleInstances(). OfType<DkmClrModuleInstance>(). Where(module => { var moduleAppDomain = module.AppDomain; return !moduleAppDomain.IsUnloaded && (moduleAppDomain.Id == appDomainId); }); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks( this DkmClrRuntimeInstance runtime, DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> previousMetadataBlocks) { // Add a dummy data item to the appdomain to add it to the disposal queue when the debugged process is shutting down. // This should prevent from attempts to use the Metadata pointer for dead debugged processes. if (appDomain.GetDataItem<AppDomainLifetimeDataItem>() == null) { appDomain.SetDataItem(DkmDataCreationDisposition.CreateNew, new AppDomainLifetimeDataItem()); } var builder = ArrayBuilder<MetadataBlock>.GetInstance(); IntPtr ptr; uint size; int index = 0; foreach (DkmClrModuleInstance module in runtime.GetModulesInAppDomain(appDomain)) { MetadataBlock block; try { ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); block = GetMetadataBlock(previousMetadataBlocks, index, ptr, size); } catch (NotImplementedException e) when (module is DkmClrNcModuleInstance) { // DkmClrNcModuleInstance.GetMetaDataBytesPtr not implemented in Dev14. throw new NotImplementedMetadataException(e); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } Debug.Assert(block.ModuleVersionId == module.Mvid); builder.Add(block); index++; } // Include "intrinsic method" assembly. ptr = runtime.GetIntrinsicAssemblyMetaDataBytesPtr(out size); builder.Add(GetMetadataBlock(previousMetadataBlocks, index, ptr, size)); return builder.ToImmutableAndFree(); } internal static ImmutableArray<MetadataBlock> GetMetadataBlocks(GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities) { ArrayBuilder<MetadataBlock>? builder = null; foreach (var missingAssemblyIdentity in missingAssemblyIdentities) { MetadataBlock block; try { uint size; IntPtr ptr; ptr = getMetaDataBytesPtrFunction(missingAssemblyIdentity, out size); Debug.Assert(size > 0); block = GetMetadataBlock(ptr, size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } if (builder == null) { builder = ArrayBuilder<MetadataBlock>.GetInstance(); } builder.Add(block); } return builder == null ? ImmutableArray<MetadataBlock>.Empty : builder.ToImmutableAndFree(); } internal static ImmutableArray<AssemblyReaders> MakeAssemblyReaders(this DkmClrInstructionAddress instructionAddress) { var builder = ArrayBuilder<AssemblyReaders>.GetInstance(); foreach (DkmClrModuleInstance module in instructionAddress.RuntimeInstance.GetModulesInAppDomain(instructionAddress.ModuleInstance.AppDomain)) { var symReader = module.GetSymReader(); if (symReader == null) { continue; } MetadataReader reader; unsafe { try { uint size; IntPtr ptr; ptr = module.GetMetaDataBytesPtr(out size); Debug.Assert(size > 0); reader = new MetadataReader((byte*)ptr, (int)size); } catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) { continue; } } builder.Add(new AssemblyReaders(reader, symReader)); } return builder.ToImmutableAndFree(); } private static unsafe MetadataBlock GetMetadataBlock(IntPtr ptr, uint size) { var reader = new MetadataReader((byte*)ptr, (int)size); var moduleDef = reader.GetModuleDefinition(); var moduleVersionId = reader.GetGuid(moduleDef.Mvid); var generationId = reader.GetGuid(moduleDef.GenerationId); return new MetadataBlock(moduleVersionId, generationId, ptr, (int)size); } private static MetadataBlock GetMetadataBlock(ImmutableArray<MetadataBlock> previousMetadataBlocks, int index, IntPtr ptr, uint size) { if (!previousMetadataBlocks.IsDefault && index < previousMetadataBlocks.Length) { var previousBlock = previousMetadataBlocks[index]; if (previousBlock.Pointer == ptr && previousBlock.Size == size) { return previousBlock; } } return GetMetadataBlock(ptr, size); } internal static object? GetSymReader(this DkmClrModuleInstance clrModule) { var module = clrModule.Module; // Null if there are no symbols. if (module == null) { return null; } // Use DkmClrModuleInstance.GetSymUnmanagedReader() // rather than DkmModule.GetSymbolInterface() since the // latter does not handle .NET Native modules. return clrModule.GetSymUnmanagedReader(); } internal static DkmCompiledClrInspectionQuery? ToQueryResult( this CompileResult? compResult, DkmCompilerId languageId, ResultProperties resultProperties, DkmClrRuntimeInstance runtimeInstance) { if (compResult == null) { return null; } Debug.Assert(compResult.Assembly != null); Debug.Assert(compResult.TypeName != null); Debug.Assert(compResult.MethodName != null); ReadOnlyCollection<byte>? customTypeInfo; Guid customTypeInfoId = compResult.GetCustomTypeInfo(out customTypeInfo); return DkmCompiledClrInspectionQuery.Create( runtimeInstance, Binary: new ReadOnlyCollection<byte>(compResult.Assembly), DataContainer: null, LanguageId: languageId, TypeName: compResult.TypeName, MethodName: compResult.MethodName, FormatSpecifiers: compResult.FormatSpecifiers, CompilationFlags: resultProperties.Flags, ResultCategory: resultProperties.Category, Access: resultProperties.AccessType, StorageType: resultProperties.StorageType, TypeModifierFlags: resultProperties.ModifierFlags, CustomTypeInfo: customTypeInfo.ToCustomTypeInfo(customTypeInfoId)); } internal static DkmClrCustomTypeInfo? ToCustomTypeInfo(this ReadOnlyCollection<byte>? payload, Guid payloadTypeId) { return (payload == null) ? null : DkmClrCustomTypeInfo.Create(payloadTypeId, payload); } internal static ResultProperties GetResultProperties<TSymbol>(this TSymbol? symbol, DkmClrCompilationResultFlags flags, bool isConstant) where TSymbol : class, ISymbolInternal { var category = (symbol != null) ? GetResultCategory(symbol.Kind) : DkmEvaluationResultCategory.Data; var accessType = (symbol != null) ? GetResultAccessType(symbol.DeclaredAccessibility) : DkmEvaluationResultAccessType.None; var storageType = (symbol != null) && symbol.IsStatic ? DkmEvaluationResultStorageType.Static : DkmEvaluationResultStorageType.None; var modifierFlags = DkmEvaluationResultTypeModifierFlags.None; if (isConstant) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Constant; } else if (symbol is null) { // No change. } else if (symbol.IsVirtual || symbol.IsAbstract || symbol.IsOverride) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Virtual; } else if (symbol.Kind == SymbolKind.Field && ((IFieldSymbolInternal)symbol).IsVolatile) { modifierFlags = DkmEvaluationResultTypeModifierFlags.Volatile; } // CONSIDER: for completeness, we could check for [MethodImpl(MethodImplOptions.Synchronized)] // and set DkmEvaluationResultTypeModifierFlags.Synchronized, but it doesn't seem to have any // impact on the UI. It is exposed through the DTE, but cscompee didn't set the flag either. return new ResultProperties(flags, category, accessType, storageType, modifierFlags); } private static DkmEvaluationResultCategory GetResultCategory(SymbolKind kind) { switch (kind) { case SymbolKind.Method: return DkmEvaluationResultCategory.Method; case SymbolKind.Property: return DkmEvaluationResultCategory.Property; default: return DkmEvaluationResultCategory.Data; } } private static DkmEvaluationResultAccessType GetResultAccessType(Accessibility accessibility) { switch (accessibility) { case Accessibility.Public: return DkmEvaluationResultAccessType.Public; case Accessibility.Protected: return DkmEvaluationResultAccessType.Protected; case Accessibility.Private: return DkmEvaluationResultAccessType.Private; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: // Dev12 treats this as "internal" case Accessibility.ProtectedAndInternal: // Dev12 treats this as "internal" return DkmEvaluationResultAccessType.Internal; case Accessibility.NotApplicable: return DkmEvaluationResultAccessType.None; default: throw ExceptionUtilities.UnexpectedValue(accessibility); } } internal static bool Includes(this DkmVariableInfoFlags flags, DkmVariableInfoFlags desired) { return (flags & desired) == desired; } internal static MetadataContext<TAssemblyContext> GetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { var dataItem = appDomain.GetDataItem<MetadataContextItem<MetadataContext<TAssemblyContext>>>(); return (dataItem == null) ? default : dataItem.MetadataContext; } internal static void SetMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain, MetadataContext<TAssemblyContext> context, bool report) where TAssemblyContext : struct { if (report) { var process = appDomain.Process; var message = DkmUserMessage.Create( process.Connection, process, DkmUserMessageOutputKind.UnfilteredOutputWindowMessage, $"EE: AppDomain {appDomain.Id}, blocks {context.MetadataBlocks.Length}, contexts {context.AssemblyContexts.Count}" + Environment.NewLine, MessageBoxFlags.MB_OK, 0); message.Post(); } appDomain.SetDataItem(DkmDataCreationDisposition.CreateAlways, new MetadataContextItem<MetadataContext<TAssemblyContext>>(context)); } internal static void RemoveMetadataContext<TAssemblyContext>(this DkmClrAppDomain appDomain) where TAssemblyContext : struct { appDomain.RemoveDataItem<MetadataContextItem<TAssemblyContext>>(); } private sealed class MetadataContextItem<TMetadataContext> : DkmDataItem where TMetadataContext : struct { internal readonly TMetadataContext MetadataContext; internal MetadataContextItem(TMetadataContext metadataContext) { this.MetadataContext = metadataContext; } } private sealed class AppDomainLifetimeDataItem : DkmDataItem { } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/CSharp/Portable/Syntax/ArrayRankSpecifierSyntax.cs
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax { public partial class ArrayRankSpecifierSyntax { public int Rank { get { return this.Sizes.Count; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ArrayRankSpecifierSyntax { public int Rank { get { return this.Sizes.Count; } } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Workspaces/Core/Portable/Serialization/SerializableSourceText.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { /// <summary> /// Represents a <see cref="SourceText"/> which can be serialized for sending to another process. The text is not /// required to be a live object in the current process, and can instead be held in temporary storage accessible by /// both processes. /// </summary> internal sealed class SerializableSourceText { /// <summary> /// The storage location for <see cref="SourceText"/>. /// </summary> /// <remarks> /// Exactly one of <see cref="Storage"/> or <see cref="Text"/> will be non-<see langword="null"/>. /// </remarks> public ITemporaryTextStorageWithName? Storage { get; } /// <summary> /// The <see cref="SourceText"/> in the current process. /// </summary> /// <remarks> /// <inheritdoc cref="Storage"/> /// </remarks> public SourceText? Text { get; } public SerializableSourceText(ITemporaryTextStorageWithName storage) : this(storage, text: null) { } public SerializableSourceText(SourceText text) : this(storage: null, text) { } private SerializableSourceText(ITemporaryTextStorageWithName? storage, SourceText? text) { Debug.Assert(storage is null != text is null); Storage = storage; Text = text; } public ImmutableArray<byte> GetChecksum() { return Text?.GetChecksum() ?? Storage!.GetChecksum(); } public async ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken) { if (Text is not null) return Text; return await Storage!.ReadTextAsync(cancellationToken).ConfigureAwait(false); } public static ValueTask<SerializableSourceText> FromTextDocumentStateAsync(TextDocumentState state, CancellationToken cancellationToken) { if (state.Storage is ITemporaryTextStorageWithName storage) { return new ValueTask<SerializableSourceText>(new SerializableSourceText(storage)); } else { return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (state, cancellationToken) => state.GetTextAsync(cancellationToken), static (text, _) => new SerializableSourceText(text), state, cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { /// <summary> /// Represents a <see cref="SourceText"/> which can be serialized for sending to another process. The text is not /// required to be a live object in the current process, and can instead be held in temporary storage accessible by /// both processes. /// </summary> internal sealed class SerializableSourceText { /// <summary> /// The storage location for <see cref="SourceText"/>. /// </summary> /// <remarks> /// Exactly one of <see cref="Storage"/> or <see cref="Text"/> will be non-<see langword="null"/>. /// </remarks> public ITemporaryTextStorageWithName? Storage { get; } /// <summary> /// The <see cref="SourceText"/> in the current process. /// </summary> /// <remarks> /// <inheritdoc cref="Storage"/> /// </remarks> public SourceText? Text { get; } public SerializableSourceText(ITemporaryTextStorageWithName storage) : this(storage, text: null) { } public SerializableSourceText(SourceText text) : this(storage: null, text) { } private SerializableSourceText(ITemporaryTextStorageWithName? storage, SourceText? text) { Debug.Assert(storage is null != text is null); Storage = storage; Text = text; } public ImmutableArray<byte> GetChecksum() { return Text?.GetChecksum() ?? Storage!.GetChecksum(); } public async ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken) { if (Text is not null) return Text; return await Storage!.ReadTextAsync(cancellationToken).ConfigureAwait(false); } public static ValueTask<SerializableSourceText> FromTextDocumentStateAsync(TextDocumentState state, CancellationToken cancellationToken) { if (state.Storage is ITemporaryTextStorageWithName storage) { return new ValueTask<SerializableSourceText>(new SerializableSourceText(storage)); } else { return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (state, cancellationToken) => state.GetTextAsync(cancellationToken), static (text, _) => new SerializableSourceText(text), state, cancellationToken); } } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/Test/Core/TempFiles/TempDirectory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public class TempDirectory { private readonly string _path; private readonly TempRoot _root; protected TempDirectory(TempRoot root) : this(CreateUniqueDirectory(TempRoot.Root), root) { } private TempDirectory(string path, TempRoot root) { Debug.Assert(path != null); Debug.Assert(root != null); _path = path; _root = root; } private static string CreateUniqueDirectory(string basePath) { while (true) { string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString()); try { Directory.CreateDirectory(dir); return dir; } catch (IOException) { // retry } } } public string Path { get { return _path; } } /// <summary> /// Creates a file in this directory. /// </summary> /// <param name="name">File name.</param> public TempFile CreateFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.CreateNew); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file or opens an existing file in this directory. /// </summary> public TempFile CreateOrOpenFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.OpenOrCreate); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file in this directory that is a copy of the specified file. /// </summary> public TempFile CopyFile(string originalPath, string name = null) { string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath)); File.Copy(originalPath, filePath); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a subdirectory in this directory. /// </summary> /// <param name="name">Directory name or unrooted directory path.</param> public TempDirectory CreateDirectory(string name) { string dirPath = System.IO.Path.Combine(_path, name); Directory.CreateDirectory(dirPath); return new TempDirectory(dirPath, _root); } public override string ToString() { return _path; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public class TempDirectory { private readonly string _path; private readonly TempRoot _root; protected TempDirectory(TempRoot root) : this(CreateUniqueDirectory(TempRoot.Root), root) { } private TempDirectory(string path, TempRoot root) { Debug.Assert(path != null); Debug.Assert(root != null); _path = path; _root = root; } private static string CreateUniqueDirectory(string basePath) { while (true) { string dir = System.IO.Path.Combine(basePath, Guid.NewGuid().ToString()); try { Directory.CreateDirectory(dir); return dir; } catch (IOException) { // retry } } } public string Path { get { return _path; } } /// <summary> /// Creates a file in this directory. /// </summary> /// <param name="name">File name.</param> public TempFile CreateFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.CreateNew); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file or opens an existing file in this directory. /// </summary> public TempFile CreateOrOpenFile(string name) { string filePath = System.IO.Path.Combine(_path, name); TempRoot.CreateStream(filePath, FileMode.OpenOrCreate); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a file in this directory that is a copy of the specified file. /// </summary> public TempFile CopyFile(string originalPath, string name = null) { string filePath = System.IO.Path.Combine(_path, name ?? System.IO.Path.GetFileName(originalPath)); File.Copy(originalPath, filePath); return _root.AddFile(new DisposableFile(filePath)); } /// <summary> /// Creates a subdirectory in this directory. /// </summary> /// <param name="name">Directory name or unrooted directory path.</param> public TempDirectory CreateDirectory(string name) { string dirPath = System.IO.Path.Combine(_path, name); Directory.CreateDirectory(dirPath); return new TempDirectory(dirPath, _root); } public override string ToString() { return _path; } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ReferenceKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ReferenceKeywordRecommender() : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsPreProcessorKeywordContext && syntaxTree.IsScript() && syntaxTree.IsBeforeFirstToken(position, 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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ReferenceKeywordRecommender() : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsPreProcessorKeywordContext && syntaxTree.IsScript() && syntaxTree.IsBeforeFirstToken(position, cancellationToken); } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/VisualStudio/CSharp/Impl/ObjectBrowser/ObjectBrowserLibraryManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class ObjectBrowserLibraryManager : AbstractObjectBrowserLibraryManager { public ObjectBrowserLibraryManager( IServiceProvider serviceProvider, IComponentModel componentModel, VisualStudioWorkspace workspace) : base(LanguageNames.CSharp, Guids.CSharpLibraryId, serviceProvider, componentModel, workspace) { } internal override AbstractDescriptionBuilder CreateDescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectListItem listItem, Project project) { return new DescriptionBuilder(description, this, listItem, project); } internal override AbstractListItemFactory CreateListItemFactory() => new ListItemFactory(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ObjectBrowser { internal class ObjectBrowserLibraryManager : AbstractObjectBrowserLibraryManager { public ObjectBrowserLibraryManager( IServiceProvider serviceProvider, IComponentModel componentModel, VisualStudioWorkspace workspace) : base(LanguageNames.CSharp, Guids.CSharpLibraryId, serviceProvider, componentModel, workspace) { } internal override AbstractDescriptionBuilder CreateDescriptionBuilder( IVsObjectBrowserDescription3 description, ObjectListItem listItem, Project project) { return new DescriptionBuilder(description, this, listItem, project); } internal override AbstractListItemFactory CreateListItemFactory() => new ListItemFactory(); } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Workspaces/Core/Portable/Shared/Utilities/BloomFilter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { 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. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/ContainsGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class ContainsGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { cancellationToken.ThrowIfCancellationRequested(); var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol != null) { foreach (var newSymbol in SymbolContainment.GetContainedSymbols(symbol)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeAsync( newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken); } } else if (node.HasCategory(CodeNodeCategories.File)) { var document = graphBuilder.GetContextDocument(node, cancellationToken); if (document != null) { foreach (var newSymbol in await SymbolContainment.GetContainedSymbolsAsync(document, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeAsync( newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken); } } } } nodesToProcess = newNodes; } return graphBuilder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class ContainsGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var nodesToProcess = context.InputNodes; for (var depth = 0; depth < context.LinkDepth; depth++) { // This is the list of nodes we created and will process var newNodes = new HashSet<GraphNode>(); foreach (var node in nodesToProcess) { cancellationToken.ThrowIfCancellationRequested(); var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol != null) { foreach (var newSymbol in SymbolContainment.GetContainedSymbols(symbol)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeAsync( newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken); } } else if (node.HasCategory(CodeNodeCategories.File)) { var document = graphBuilder.GetContextDocument(node, cancellationToken); if (document != null) { foreach (var newSymbol in await SymbolContainment.GetContainedSymbolsAsync(document, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newNode = await graphBuilder.AddNodeAsync( newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode, cancellationToken); } } } } nodesToProcess = newNodes; } return graphBuilder; } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Features/Core/Portable/NavigateTo/IRemoteNavigateToSearchService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Storage; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface IRemoteNavigateToSearchService { ValueTask SearchFullyLoadedDocumentAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask SearchFullyLoadedProjectAsync(PinnedSolutionInfo solutionInfo, ProjectId projectId, ImmutableArray<DocumentId> priorityDocumentIds, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask SearchCachedDocumentsAsync(ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, StorageDatabase database, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask HydrateAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken); public interface ICallback { ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result); } } [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteNavigateToSearchService)), Shared] internal sealed class NavigateToSearchServiceServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteNavigateToSearchService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigateToSearchServiceServerCallbackDispatcher() { } private new NavigateToSearchServiceCallback GetCallback(RemoteServiceCallbackId callbackId) => (NavigateToSearchServiceCallback)base.GetCallback(callbackId); public ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result) => GetCallback(callbackId).OnResultFoundAsync(result); } internal sealed class NavigateToSearchServiceCallback { private readonly Func<RoslynNavigateToItem, Task> _onResultFound; public NavigateToSearchServiceCallback(Func<RoslynNavigateToItem, Task> onResultFound) { _onResultFound = onResultFound; } public async ValueTask OnResultFoundAsync(RoslynNavigateToItem result) => await _onResultFound(result).ConfigureAwait(false); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Storage; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface IRemoteNavigateToSearchService { ValueTask SearchFullyLoadedDocumentAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask SearchFullyLoadedProjectAsync(PinnedSolutionInfo solutionInfo, ProjectId projectId, ImmutableArray<DocumentId> priorityDocumentIds, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask SearchCachedDocumentsAsync(ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, StorageDatabase database, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask HydrateAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken); public interface ICallback { ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result); } } [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteNavigateToSearchService)), Shared] internal sealed class NavigateToSearchServiceServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteNavigateToSearchService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NavigateToSearchServiceServerCallbackDispatcher() { } private new NavigateToSearchServiceCallback GetCallback(RemoteServiceCallbackId callbackId) => (NavigateToSearchServiceCallback)base.GetCallback(callbackId); public ValueTask OnResultFoundAsync(RemoteServiceCallbackId callbackId, RoslynNavigateToItem result) => GetCallback(callbackId).OnResultFoundAsync(result); } internal sealed class NavigateToSearchServiceCallback { private readonly Func<RoslynNavigateToItem, Task> _onResultFound; public NavigateToSearchServiceCallback(Func<RoslynNavigateToItem, Task> onResultFound) { _onResultFound = onResultFound; } public async ValueTask OnResultFoundAsync(RoslynNavigateToItem result) => await _onResultFound(result).ConfigureAwait(false); } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/TextEditApplication.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class TextEditApplication { internal static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); var changes = newText.GetTextChanges(oldText); UpdateText(changes.ToImmutableArray(), buffer, oldSnapshot, oldText, options); } public static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); UpdateText(textChanges, buffer, oldSnapshot, oldText, options); } private static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, ITextSnapshot oldSnapshot, SourceText oldText, EditOptions options) { using var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null); if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace)) { var undoService = workspace.Services.GetRequiredService<ISourceTextUndoService>(); undoService.BeginUndoTransaction(oldSnapshot); } foreach (var change in textChanges) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.ApplyAndLogExceptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class TextEditApplication { internal static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); var changes = newText.GetTextChanges(oldText); UpdateText(changes.ToImmutableArray(), buffer, oldSnapshot, oldText, options); } public static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); UpdateText(textChanges, buffer, oldSnapshot, oldText, options); } private static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, ITextSnapshot oldSnapshot, SourceText oldText, EditOptions options) { using var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null); if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace)) { var undoService = workspace.Services.GetRequiredService<ISourceTextUndoService>(); undoService.BeginUndoTransaction(oldSnapshot); } foreach (var change in textChanges) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.ApplyAndLogExceptions(); } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Tools/IdeCoreBenchmarks/FormatterBenchmarks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FormatterBenchmarks { private readonly int _iterationCount = 5; private Document _document; private OptionSet _options; [GlobalSetup] public void GlobalSetup() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var csFilePath = Path.Combine(roslynRoot, @"src\Compilers\CSharp\Portable\Generated\Syntax.xml.Syntax.Generated.cs"); if (!File.Exists(csFilePath)) { throw new ArgumentException(); } // Remove some newlines var text = File.ReadAllText(csFilePath).Replace("<auto-generated />", "") .Replace($"{{{Environment.NewLine}{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}{Environment.NewLine}", "}") .Replace($"{{{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}", "}") .Replace($";{Environment.NewLine}", ";"); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", text); var document = solution.GetDocument(documentId); var root = document.GetSyntaxRootAsync(CancellationToken.None).Result.WithAdditionalAnnotations(Formatter.Annotation); solution = solution.WithDocumentSyntaxRoot(documentId, root); _document = solution.GetDocument(documentId); _options = _document.GetOptionsAsync().Result .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, true) .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false) .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false); } [Benchmark] public void FormatSyntaxNode() { for (int i = 0; i < _iterationCount; ++i) { var formattedDoc = Formatter.FormatAsync(_document, Formatter.Annotation, _options, CancellationToken.None).Result; var formattedRoot = formattedDoc.GetSyntaxRootAsync(CancellationToken.None).Result; _ = formattedRoot.DescendantNodesAndSelf().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. #nullable disable using System; using System.Collections.Immutable; using System.IO; using System.Threading; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FormatterBenchmarks { private readonly int _iterationCount = 5; private Document _document; private OptionSet _options; [GlobalSetup] public void GlobalSetup() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var csFilePath = Path.Combine(roslynRoot, @"src\Compilers\CSharp\Portable\Generated\Syntax.xml.Syntax.Generated.cs"); if (!File.Exists(csFilePath)) { throw new ArgumentException(); } // Remove some newlines var text = File.ReadAllText(csFilePath).Replace("<auto-generated />", "") .Replace($"{{{Environment.NewLine}{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}{Environment.NewLine}", "}") .Replace($"{{{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}", "}") .Replace($";{Environment.NewLine}", ";"); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", text); var document = solution.GetDocument(documentId); var root = document.GetSyntaxRootAsync(CancellationToken.None).Result.WithAdditionalAnnotations(Formatter.Annotation); solution = solution.WithDocumentSyntaxRoot(documentId, root); _document = solution.GetDocument(documentId); _options = _document.GetOptionsAsync().Result .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, true) .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false) .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false); } [Benchmark] public void FormatSyntaxNode() { for (int i = 0; i < _iterationCount; ++i) { var formattedDoc = Formatter.FormatAsync(_document, Formatter.Annotation, _options, CancellationToken.None).Result; var formattedRoot = formattedDoc.GetSyntaxRootAsync(CancellationToken.None).Result; _ = formattedRoot.DescendantNodesAndSelf().ToImmutableArray(); } } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/CSharp/Portable/Errors/XmlSyntaxDiagnosticInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo { static XmlSyntaxDiagnosticInfo() { ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), r => new XmlSyntaxDiagnosticInfo(r)); } private readonly XmlParseErrorCode _xmlErrorCode; internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args) : this(0, 0, code, args) { } internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args) : base(offset, width, ErrorCode.WRN_XMLParseError, args) { _xmlErrorCode = code; } #region Serialization protected override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteUInt32((uint)_xmlErrorCode); } private XmlSyntaxDiagnosticInfo(ObjectReader reader) : base(reader) { _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32(); } #endregion public override string GetMessage(IFormatProvider formatProvider = null) { var culture = formatProvider as CultureInfo; string messagePrefix = this.MessageProvider.LoadMessage(this.Code, culture); string message = ErrorFacts.GetMessage(_xmlErrorCode, culture); System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(message)); if (this.Arguments == null || this.Arguments.Length == 0) { return String.Format(formatProvider, messagePrefix, message); } return String.Format(formatProvider, String.Format(formatProvider, messagePrefix, message), GetArgumentsToUse(formatProvider)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class XmlSyntaxDiagnosticInfo : SyntaxDiagnosticInfo { static XmlSyntaxDiagnosticInfo() { ObjectBinder.RegisterTypeReader(typeof(XmlSyntaxDiagnosticInfo), r => new XmlSyntaxDiagnosticInfo(r)); } private readonly XmlParseErrorCode _xmlErrorCode; internal XmlSyntaxDiagnosticInfo(XmlParseErrorCode code, params object[] args) : this(0, 0, code, args) { } internal XmlSyntaxDiagnosticInfo(int offset, int width, XmlParseErrorCode code, params object[] args) : base(offset, width, ErrorCode.WRN_XMLParseError, args) { _xmlErrorCode = code; } #region Serialization protected override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteUInt32((uint)_xmlErrorCode); } private XmlSyntaxDiagnosticInfo(ObjectReader reader) : base(reader) { _xmlErrorCode = (XmlParseErrorCode)reader.ReadUInt32(); } #endregion public override string GetMessage(IFormatProvider formatProvider = null) { var culture = formatProvider as CultureInfo; string messagePrefix = this.MessageProvider.LoadMessage(this.Code, culture); string message = ErrorFacts.GetMessage(_xmlErrorCode, culture); System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(message)); if (this.Arguments == null || this.Arguments.Length == 0) { return String.Format(formatProvider, messagePrefix, message); } return String.Format(formatProvider, String.Format(formatProvider, messagePrefix, message), GetArgumentsToUse(formatProvider)); } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolEquivalenceComparer.GetHashCodeVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class SymbolEquivalenceComparer { private class GetHashCodeVisitor { private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; private readonly bool _compareMethodTypeParametersByIndex; private readonly bool _objectAndDynamicCompareEqually; private readonly Func<int, IParameterSymbol, int> _parameterAggregator; private readonly Func<int, ISymbol, int> _symbolAggregator; public GetHashCodeVisitor( SymbolEquivalenceComparer symbolEquivalenceComparer, bool compareMethodTypeParametersByIndex, bool objectAndDynamicCompareEqually) { _symbolEquivalenceComparer = symbolEquivalenceComparer; _compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex; _objectAndDynamicCompareEqually = objectAndDynamicCompareEqually; _parameterAggregator = (acc, sym) => Hash.Combine(symbolEquivalenceComparer.ParameterEquivalenceComparer.GetHashCode(sym), acc); _symbolAggregator = (acc, sym) => GetHashCode(sym, acc); } public int GetHashCode(ISymbol? x, int currentHash) { if (x == null) return 0; x = UnwrapAlias(x); // Special case. If we're comparing signatures then we want to compare 'object' // and 'dynamic' as the same. However, since they're different types, we don't // want to bail out using the above check. if (x.Kind == SymbolKind.DynamicType || (_objectAndDynamicCompareEqually && IsObjectType(x))) { return Hash.Combine(GetNullableAnnotationsHashCode((ITypeSymbol)x), Hash.Combine(typeof(IDynamicTypeSymbol), currentHash)); } return GetHashCodeWorker(x, currentHash); } private int GetNullableAnnotationsHashCode(ITypeSymbol type) => _symbolEquivalenceComparer._ignoreNullableAnnotations ? 0 : type.NullableAnnotation.GetHashCode(); private int GetHashCodeWorker(ISymbol x, int currentHash) => x.Kind switch { SymbolKind.ArrayType => CombineHashCodes((IArrayTypeSymbol)x, currentHash), SymbolKind.Assembly => CombineHashCodes((IAssemblySymbol)x, currentHash), SymbolKind.Event => CombineHashCodes((IEventSymbol)x, currentHash), SymbolKind.Field => CombineHashCodes((IFieldSymbol)x, currentHash), SymbolKind.Label => CombineHashCodes((ILabelSymbol)x, currentHash), SymbolKind.Local => CombineHashCodes((ILocalSymbol)x, currentHash), SymbolKind.Method => CombineHashCodes((IMethodSymbol)x, currentHash), SymbolKind.NetModule => CombineHashCodes((IModuleSymbol)x, currentHash), SymbolKind.NamedType => CombineHashCodes((INamedTypeSymbol)x, currentHash), SymbolKind.Namespace => CombineHashCodes((INamespaceSymbol)x, currentHash), SymbolKind.Parameter => CombineHashCodes((IParameterSymbol)x, currentHash), SymbolKind.PointerType => CombineHashCodes((IPointerTypeSymbol)x, currentHash), SymbolKind.Property => CombineHashCodes((IPropertySymbol)x, currentHash), SymbolKind.RangeVariable => CombineHashCodes((IRangeVariableSymbol)x, currentHash), SymbolKind.TypeParameter => CombineHashCodes((ITypeParameterSymbol)x, currentHash), SymbolKind.Preprocessing => CombineHashCodes((IPreprocessingSymbol)x, currentHash), _ => -1, }; private int CombineHashCodes(IArrayTypeSymbol x, int currentHash) { return Hash.Combine(GetNullableAnnotationsHashCode(x), Hash.Combine(x.Rank, GetHashCode(x.ElementType, currentHash))); } private int CombineHashCodes(IAssemblySymbol x, int currentHash) => Hash.Combine(_symbolEquivalenceComparer._assemblyComparerOpt?.GetHashCode(x) ?? 0, currentHash); private int CombineHashCodes(IFieldSymbol x, int currentHash) { return Hash.Combine(x.Name, GetHashCode(x.ContainingSymbol, currentHash)); } private static int CombineHashCodes(ILabelSymbol x, int currentHash) { return Hash.Combine(x.Name, Hash.Combine(x.Locations.FirstOrDefault(), currentHash)); } private static int CombineHashCodes(ILocalSymbol x, int currentHash) => Hash.Combine(x.Locations.FirstOrDefault(), currentHash); private static int CombineHashCodes<T>(ImmutableArray<T> array, int currentHash, Func<int, T, int> func) => array.Aggregate<int, T>(currentHash, func); private int CombineHashCodes(IMethodSymbol x, int currentHash) { currentHash = Hash.Combine(x.MetadataName, currentHash); if (x.MethodKind == MethodKind.AnonymousFunction) { return Hash.Combine(x.Locations.FirstOrDefault(), currentHash); } currentHash = Hash.Combine(IsPartialMethodImplementationPart(x), Hash.Combine(IsPartialMethodDefinitionPart(x), Hash.Combine(x.IsDefinition, Hash.Combine(IsConstructedFromSelf(x), Hash.Combine(x.Arity, Hash.Combine(x.Parameters.Length, Hash.Combine(x.Name, currentHash))))))); var checkContainingType = CheckContainingType(x); if (checkContainingType) { currentHash = GetHashCode(x.ContainingSymbol, currentHash); } currentHash = CombineHashCodes(x.Parameters, currentHash, _parameterAggregator); return IsConstructedFromSelf(x) ? currentHash : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator); } private int CombineHashCodes(IModuleSymbol x, int currentHash) => CombineHashCodes(x.ContainingAssembly, Hash.Combine(x.Name, currentHash)); private int CombineHashCodes(INamedTypeSymbol x, int currentHash) { currentHash = CombineNamedTypeHashCode(x, currentHash); if (x is IErrorTypeSymbol errorType) { foreach (var candidate in errorType.CandidateSymbols) { if (candidate is INamedTypeSymbol candidateNamedType) { currentHash = CombineNamedTypeHashCode(candidateNamedType, currentHash); } } } return currentHash; } private int CombineNamedTypeHashCode(INamedTypeSymbol x, int currentHash) { if (x.IsTupleType) { return Hash.Combine(currentHash, Hash.CombineValues(x.TupleElements)); } // If we want object and dynamic to be the same, and this is 'object', then return // the same hash we do for 'dynamic'. currentHash = Hash.Combine((int)GetTypeKind(x), Hash.Combine(IsConstructedFromSelf(x), Hash.Combine(x.Arity, Hash.Combine(x.Name, Hash.Combine(x.IsAnonymousType, Hash.Combine(x.IsUnboundGenericType, Hash.Combine(GetNullableAnnotationsHashCode(x), GetHashCode(x.ContainingSymbol, currentHash)))))))); if (x.IsAnonymousType) { return CombineAnonymousTypeHashCode(x, currentHash); } return IsConstructedFromSelf(x) || x.IsUnboundGenericType ? currentHash : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator); } private int CombineAnonymousTypeHashCode(INamedTypeSymbol x, int currentHash) { if (x.TypeKind == TypeKind.Delegate) { return GetHashCode(x.DelegateInvokeMethod, currentHash); } else { var xMembers = x.GetValidAnonymousTypeProperties(); return xMembers.Aggregate(currentHash, (a, p) => { return Hash.Combine(p.Name, Hash.Combine(p.IsReadOnly, GetHashCode(p.Type, a))); }); } } private int CombineHashCodes(INamespaceSymbol x, int currentHash) { if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null) { // Exclude global namespace's container's hash when assemblies can differ. return Hash.Combine(x.Name, currentHash); } return Hash.Combine(x.IsGlobalNamespace, Hash.Combine(x.Name, GetHashCode(x.ContainingSymbol, currentHash))); } private int CombineHashCodes(IParameterSymbol x, int currentHash) { return Hash.Combine(x.IsRefOrOut(), Hash.Combine(x.Name, GetHashCode(x.Type, GetHashCode(x.ContainingSymbol, currentHash)))); } private int CombineHashCodes(IPointerTypeSymbol x, int currentHash) { return Hash.Combine(typeof(IPointerTypeSymbol).GetHashCode(), GetHashCode(x.PointedAtType, currentHash)); } private int CombineHashCodes(IPropertySymbol x, int currentHash) { currentHash = Hash.Combine(x.IsIndexer, Hash.Combine(x.Name, Hash.Combine(x.Parameters.Length, GetHashCode(x.ContainingSymbol, currentHash)))); return CombineHashCodes(x.Parameters, currentHash, _parameterAggregator); } private int CombineHashCodes(IEventSymbol x, int currentHash) { return Hash.Combine(x.Name, GetHashCode(x.ContainingSymbol, currentHash)); } public int CombineHashCodes(ITypeParameterSymbol x, int currentHash) { Debug.Assert( (x.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(x.DeclaringMethod!)) || (x.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(x.ContainingType)) || x.TypeParameterKind == TypeParameterKind.Cref); currentHash = Hash.Combine(x.Ordinal, Hash.Combine((int)x.TypeParameterKind, currentHash)); if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex) { return currentHash; } if (x.TypeParameterKind == TypeParameterKind.Type && x.ContainingType.IsAnonymousType) { // Anonymous type type parameters compare by index as well to prevent // recursion. return currentHash; } if (x.TypeParameterKind == TypeParameterKind.Cref) { return currentHash; } return GetHashCode(x.ContainingSymbol, currentHash); } private static int CombineHashCodes(IRangeVariableSymbol x, int currentHash) => Hash.Combine(x.Locations.FirstOrDefault(), currentHash); private static int CombineHashCodes(IPreprocessingSymbol x, int currentHash) => Hash.Combine(x.GetHashCode(), currentHash); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class SymbolEquivalenceComparer { private class GetHashCodeVisitor { private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; private readonly bool _compareMethodTypeParametersByIndex; private readonly bool _objectAndDynamicCompareEqually; private readonly Func<int, IParameterSymbol, int> _parameterAggregator; private readonly Func<int, ISymbol, int> _symbolAggregator; public GetHashCodeVisitor( SymbolEquivalenceComparer symbolEquivalenceComparer, bool compareMethodTypeParametersByIndex, bool objectAndDynamicCompareEqually) { _symbolEquivalenceComparer = symbolEquivalenceComparer; _compareMethodTypeParametersByIndex = compareMethodTypeParametersByIndex; _objectAndDynamicCompareEqually = objectAndDynamicCompareEqually; _parameterAggregator = (acc, sym) => Hash.Combine(symbolEquivalenceComparer.ParameterEquivalenceComparer.GetHashCode(sym), acc); _symbolAggregator = (acc, sym) => GetHashCode(sym, acc); } public int GetHashCode(ISymbol? x, int currentHash) { if (x == null) return 0; x = UnwrapAlias(x); // Special case. If we're comparing signatures then we want to compare 'object' // and 'dynamic' as the same. However, since they're different types, we don't // want to bail out using the above check. if (x.Kind == SymbolKind.DynamicType || (_objectAndDynamicCompareEqually && IsObjectType(x))) { return Hash.Combine(GetNullableAnnotationsHashCode((ITypeSymbol)x), Hash.Combine(typeof(IDynamicTypeSymbol), currentHash)); } return GetHashCodeWorker(x, currentHash); } private int GetNullableAnnotationsHashCode(ITypeSymbol type) => _symbolEquivalenceComparer._ignoreNullableAnnotations ? 0 : type.NullableAnnotation.GetHashCode(); private int GetHashCodeWorker(ISymbol x, int currentHash) => x.Kind switch { SymbolKind.ArrayType => CombineHashCodes((IArrayTypeSymbol)x, currentHash), SymbolKind.Assembly => CombineHashCodes((IAssemblySymbol)x, currentHash), SymbolKind.Event => CombineHashCodes((IEventSymbol)x, currentHash), SymbolKind.Field => CombineHashCodes((IFieldSymbol)x, currentHash), SymbolKind.Label => CombineHashCodes((ILabelSymbol)x, currentHash), SymbolKind.Local => CombineHashCodes((ILocalSymbol)x, currentHash), SymbolKind.Method => CombineHashCodes((IMethodSymbol)x, currentHash), SymbolKind.NetModule => CombineHashCodes((IModuleSymbol)x, currentHash), SymbolKind.NamedType => CombineHashCodes((INamedTypeSymbol)x, currentHash), SymbolKind.Namespace => CombineHashCodes((INamespaceSymbol)x, currentHash), SymbolKind.Parameter => CombineHashCodes((IParameterSymbol)x, currentHash), SymbolKind.PointerType => CombineHashCodes((IPointerTypeSymbol)x, currentHash), SymbolKind.Property => CombineHashCodes((IPropertySymbol)x, currentHash), SymbolKind.RangeVariable => CombineHashCodes((IRangeVariableSymbol)x, currentHash), SymbolKind.TypeParameter => CombineHashCodes((ITypeParameterSymbol)x, currentHash), SymbolKind.Preprocessing => CombineHashCodes((IPreprocessingSymbol)x, currentHash), _ => -1, }; private int CombineHashCodes(IArrayTypeSymbol x, int currentHash) { return Hash.Combine(GetNullableAnnotationsHashCode(x), Hash.Combine(x.Rank, GetHashCode(x.ElementType, currentHash))); } private int CombineHashCodes(IAssemblySymbol x, int currentHash) => Hash.Combine(_symbolEquivalenceComparer._assemblyComparerOpt?.GetHashCode(x) ?? 0, currentHash); private int CombineHashCodes(IFieldSymbol x, int currentHash) { return Hash.Combine(x.Name, GetHashCode(x.ContainingSymbol, currentHash)); } private static int CombineHashCodes(ILabelSymbol x, int currentHash) { return Hash.Combine(x.Name, Hash.Combine(x.Locations.FirstOrDefault(), currentHash)); } private static int CombineHashCodes(ILocalSymbol x, int currentHash) => Hash.Combine(x.Locations.FirstOrDefault(), currentHash); private static int CombineHashCodes<T>(ImmutableArray<T> array, int currentHash, Func<int, T, int> func) => array.Aggregate<int, T>(currentHash, func); private int CombineHashCodes(IMethodSymbol x, int currentHash) { currentHash = Hash.Combine(x.MetadataName, currentHash); if (x.MethodKind == MethodKind.AnonymousFunction) { return Hash.Combine(x.Locations.FirstOrDefault(), currentHash); } currentHash = Hash.Combine(IsPartialMethodImplementationPart(x), Hash.Combine(IsPartialMethodDefinitionPart(x), Hash.Combine(x.IsDefinition, Hash.Combine(IsConstructedFromSelf(x), Hash.Combine(x.Arity, Hash.Combine(x.Parameters.Length, Hash.Combine(x.Name, currentHash))))))); var checkContainingType = CheckContainingType(x); if (checkContainingType) { currentHash = GetHashCode(x.ContainingSymbol, currentHash); } currentHash = CombineHashCodes(x.Parameters, currentHash, _parameterAggregator); return IsConstructedFromSelf(x) ? currentHash : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator); } private int CombineHashCodes(IModuleSymbol x, int currentHash) => CombineHashCodes(x.ContainingAssembly, Hash.Combine(x.Name, currentHash)); private int CombineHashCodes(INamedTypeSymbol x, int currentHash) { currentHash = CombineNamedTypeHashCode(x, currentHash); if (x is IErrorTypeSymbol errorType) { foreach (var candidate in errorType.CandidateSymbols) { if (candidate is INamedTypeSymbol candidateNamedType) { currentHash = CombineNamedTypeHashCode(candidateNamedType, currentHash); } } } return currentHash; } private int CombineNamedTypeHashCode(INamedTypeSymbol x, int currentHash) { if (x.IsTupleType) { return Hash.Combine(currentHash, Hash.CombineValues(x.TupleElements)); } // If we want object and dynamic to be the same, and this is 'object', then return // the same hash we do for 'dynamic'. currentHash = Hash.Combine((int)GetTypeKind(x), Hash.Combine(IsConstructedFromSelf(x), Hash.Combine(x.Arity, Hash.Combine(x.Name, Hash.Combine(x.IsAnonymousType, Hash.Combine(x.IsUnboundGenericType, Hash.Combine(GetNullableAnnotationsHashCode(x), GetHashCode(x.ContainingSymbol, currentHash)))))))); if (x.IsAnonymousType) { return CombineAnonymousTypeHashCode(x, currentHash); } return IsConstructedFromSelf(x) || x.IsUnboundGenericType ? currentHash : CombineHashCodes(x.TypeArguments, currentHash, _symbolAggregator); } private int CombineAnonymousTypeHashCode(INamedTypeSymbol x, int currentHash) { if (x.TypeKind == TypeKind.Delegate) { return GetHashCode(x.DelegateInvokeMethod, currentHash); } else { var xMembers = x.GetValidAnonymousTypeProperties(); return xMembers.Aggregate(currentHash, (a, p) => { return Hash.Combine(p.Name, Hash.Combine(p.IsReadOnly, GetHashCode(p.Type, a))); }); } } private int CombineHashCodes(INamespaceSymbol x, int currentHash) { if (x.IsGlobalNamespace && _symbolEquivalenceComparer._assemblyComparerOpt == null) { // Exclude global namespace's container's hash when assemblies can differ. return Hash.Combine(x.Name, currentHash); } return Hash.Combine(x.IsGlobalNamespace, Hash.Combine(x.Name, GetHashCode(x.ContainingSymbol, currentHash))); } private int CombineHashCodes(IParameterSymbol x, int currentHash) { return Hash.Combine(x.IsRefOrOut(), Hash.Combine(x.Name, GetHashCode(x.Type, GetHashCode(x.ContainingSymbol, currentHash)))); } private int CombineHashCodes(IPointerTypeSymbol x, int currentHash) { return Hash.Combine(typeof(IPointerTypeSymbol).GetHashCode(), GetHashCode(x.PointedAtType, currentHash)); } private int CombineHashCodes(IPropertySymbol x, int currentHash) { currentHash = Hash.Combine(x.IsIndexer, Hash.Combine(x.Name, Hash.Combine(x.Parameters.Length, GetHashCode(x.ContainingSymbol, currentHash)))); return CombineHashCodes(x.Parameters, currentHash, _parameterAggregator); } private int CombineHashCodes(IEventSymbol x, int currentHash) { return Hash.Combine(x.Name, GetHashCode(x.ContainingSymbol, currentHash)); } public int CombineHashCodes(ITypeParameterSymbol x, int currentHash) { Debug.Assert( (x.TypeParameterKind == TypeParameterKind.Method && IsConstructedFromSelf(x.DeclaringMethod!)) || (x.TypeParameterKind == TypeParameterKind.Type && IsConstructedFromSelf(x.ContainingType)) || x.TypeParameterKind == TypeParameterKind.Cref); currentHash = Hash.Combine(x.Ordinal, Hash.Combine((int)x.TypeParameterKind, currentHash)); if (x.TypeParameterKind == TypeParameterKind.Method && _compareMethodTypeParametersByIndex) { return currentHash; } if (x.TypeParameterKind == TypeParameterKind.Type && x.ContainingType.IsAnonymousType) { // Anonymous type type parameters compare by index as well to prevent // recursion. return currentHash; } if (x.TypeParameterKind == TypeParameterKind.Cref) { return currentHash; } return GetHashCode(x.ContainingSymbol, currentHash); } private static int CombineHashCodes(IRangeVariableSymbol x, int currentHash) => Hash.Combine(x.Locations.FirstOrDefault(), currentHash); private static int CombineHashCodes(IPreprocessingSymbol x, int currentHash) => Hash.Combine(x.GetHashCode(), currentHash); } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/Core/Portable/InternalUtilities/CommandLineUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; namespace Roslyn.Utilities { internal static class CommandLineUtilities { /// <summary> /// Split a command line by the same rules as Main would get the commands except the original /// state of backslashes and quotes are preserved. For example in normal Windows command line /// parsing the following command lines would produce equivalent Main arguments: /// /// - /r:a,b /// - /r:"a,b" /// /// This method will differ as the latter will have the quotes preserved. The only case where /// quotes are removed is when the entire argument is surrounded by quotes without any inner /// quotes. /// </summary> /// <remarks> /// Rules for command line parsing, according to MSDN: /// /// Arguments are delimited by white space, which is either a space or a tab. /// /// A string surrounded by double quotation marks ("string") is interpreted /// as a single argument, regardless of white space contained within. /// A quoted string can be embedded in an argument. /// /// A double quotation mark preceded by a backslash (\") is interpreted as a /// literal double quotation mark character ("). /// /// Backslashes are interpreted literally, unless they immediately precede a /// double quotation mark. /// /// If an even number of backslashes is followed by a double quotation mark, /// one backslash is placed in the argv array for every pair of backslashes, /// and the double quotation mark is interpreted as a string delimiter. /// /// If an odd number of backslashes is followed by a double quotation mark, /// one backslash is placed in the argv array for every pair of backslashes, /// and the double quotation mark is "escaped" by the remaining backslash, /// causing a literal double quotation mark (") to be placed in argv. /// </remarks> public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments) { return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _); } public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar) { var list = new List<string>(); SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar); return list; } public static void SplitCommandLineIntoArguments(ReadOnlySpan<char> commandLine, bool removeHashComments, StringBuilder builder, List<string> list, out char? illegalChar) { var i = 0; builder.Length = 0; illegalChar = null; while (i < commandLine.Length) { while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i])) { i++; } if (i == commandLine.Length) { break; } if (commandLine[i] == '#' && removeHashComments) { break; } var quoteCount = 0; builder.Length = 0; while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0))) { var current = commandLine[i]; switch (current) { case '\\': { var slashCount = 0; do { builder.Append(commandLine[i]); i++; slashCount++; } while (i < commandLine.Length && commandLine[i] == '\\'); // Slashes not followed by a quote character can be ignored for now if (i >= commandLine.Length || commandLine[i] != '"') { break; } // If there is an odd number of slashes then it is escaping the quote // otherwise it is just a quote. if (slashCount % 2 == 0) { quoteCount++; } builder.Append('"'); i++; break; } case '"': builder.Append(current); quoteCount++; i++; break; default: if ((current >= 0x1 && current <= 0x1f) || current == '|') { if (illegalChar == null) { illegalChar = current; } } else { builder.Append(current); } i++; break; } } // If the quote string is surrounded by quotes with no interior quotes then // remove the quotes here. if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"') { builder.Remove(0, length: 1); builder.Remove(builder.Length - 1, length: 1); } if (builder.Length > 0) { list.Add(builder.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.Collections.Generic; using System.Text; namespace Roslyn.Utilities { internal static class CommandLineUtilities { /// <summary> /// Split a command line by the same rules as Main would get the commands except the original /// state of backslashes and quotes are preserved. For example in normal Windows command line /// parsing the following command lines would produce equivalent Main arguments: /// /// - /r:a,b /// - /r:"a,b" /// /// This method will differ as the latter will have the quotes preserved. The only case where /// quotes are removed is when the entire argument is surrounded by quotes without any inner /// quotes. /// </summary> /// <remarks> /// Rules for command line parsing, according to MSDN: /// /// Arguments are delimited by white space, which is either a space or a tab. /// /// A string surrounded by double quotation marks ("string") is interpreted /// as a single argument, regardless of white space contained within. /// A quoted string can be embedded in an argument. /// /// A double quotation mark preceded by a backslash (\") is interpreted as a /// literal double quotation mark character ("). /// /// Backslashes are interpreted literally, unless they immediately precede a /// double quotation mark. /// /// If an even number of backslashes is followed by a double quotation mark, /// one backslash is placed in the argv array for every pair of backslashes, /// and the double quotation mark is interpreted as a string delimiter. /// /// If an odd number of backslashes is followed by a double quotation mark, /// one backslash is placed in the argv array for every pair of backslashes, /// and the double quotation mark is "escaped" by the remaining backslash, /// causing a literal double quotation mark (") to be placed in argv. /// </remarks> public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments) { return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _); } public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar) { var list = new List<string>(); SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar); return list; } public static void SplitCommandLineIntoArguments(ReadOnlySpan<char> commandLine, bool removeHashComments, StringBuilder builder, List<string> list, out char? illegalChar) { var i = 0; builder.Length = 0; illegalChar = null; while (i < commandLine.Length) { while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i])) { i++; } if (i == commandLine.Length) { break; } if (commandLine[i] == '#' && removeHashComments) { break; } var quoteCount = 0; builder.Length = 0; while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0))) { var current = commandLine[i]; switch (current) { case '\\': { var slashCount = 0; do { builder.Append(commandLine[i]); i++; slashCount++; } while (i < commandLine.Length && commandLine[i] == '\\'); // Slashes not followed by a quote character can be ignored for now if (i >= commandLine.Length || commandLine[i] != '"') { break; } // If there is an odd number of slashes then it is escaping the quote // otherwise it is just a quote. if (slashCount % 2 == 0) { quoteCount++; } builder.Append('"'); i++; break; } case '"': builder.Append(current); quoteCount++; i++; break; default: if ((current >= 0x1 && current <= 0x1f) || current == '|') { if (illegalChar == null) { illegalChar = current; } } else { builder.Append(current); } i++; break; } } // If the quote string is surrounded by quotes with no interior quotes then // remove the quotes here. if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"') { builder.Remove(0, length: 1); builder.Remove(builder.Length - 1, length: 1); } if (builder.Length > 0) { list.Add(builder.ToString()); } } } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationAsyncResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // D:\Roslyn\Main\Open\Binaries\Debug\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public struct DkmEvaluationAsyncResult { private readonly DkmEvaluationResult _result; public DkmEvaluationAsyncResult(DkmEvaluationResult Result) : this() { if (Result == null) { throw new ArgumentNullException(nameof(Result)); } _result = Result; } public int ErrorCode { get { throw new NotImplementedException(); } } public DkmEvaluationResult Result { get { return _result; } } internal Exception Exception { get; set; } public static DkmEvaluationAsyncResult CreateErrorResult(Exception exception) { return new DkmEvaluationAsyncResult() { Exception = exception }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // D:\Roslyn\Main\Open\Binaries\Debug\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public struct DkmEvaluationAsyncResult { private readonly DkmEvaluationResult _result; public DkmEvaluationAsyncResult(DkmEvaluationResult Result) : this() { if (Result == null) { throw new ArgumentNullException(nameof(Result)); } _result = Result; } public int ErrorCode { get { throw new NotImplementedException(); } } public DkmEvaluationResult Result { get { return _result; } } internal Exception Exception { get; set; } public static DkmEvaluationAsyncResult CreateErrorResult(Exception exception) { return new DkmEvaluationAsyncResult() { Exception = exception }; } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptInlineRenameReplacementKindHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { internal static class VSTypeScriptInlineRenameReplacementKindHelpers { public static VSTypeScriptInlineRenameReplacementKind ConvertFrom(InlineRenameReplacementKind kind) { return kind switch { InlineRenameReplacementKind.NoConflict => VSTypeScriptInlineRenameReplacementKind.NoConflict, InlineRenameReplacementKind.ResolvedReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict, InlineRenameReplacementKind.ResolvedNonReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict, InlineRenameReplacementKind.UnresolvedConflict => VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict, InlineRenameReplacementKind.Complexified => VSTypeScriptInlineRenameReplacementKind.Complexified, _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } public static InlineRenameReplacementKind ConvertTo(VSTypeScriptInlineRenameReplacementKind kind) { return kind switch { VSTypeScriptInlineRenameReplacementKind.NoConflict => InlineRenameReplacementKind.NoConflict, VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict => InlineRenameReplacementKind.ResolvedReferenceConflict, VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict => InlineRenameReplacementKind.ResolvedNonReferenceConflict, VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict => InlineRenameReplacementKind.UnresolvedConflict, VSTypeScriptInlineRenameReplacementKind.Complexified => InlineRenameReplacementKind.Complexified, _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { internal static class VSTypeScriptInlineRenameReplacementKindHelpers { public static VSTypeScriptInlineRenameReplacementKind ConvertFrom(InlineRenameReplacementKind kind) { return kind switch { InlineRenameReplacementKind.NoConflict => VSTypeScriptInlineRenameReplacementKind.NoConflict, InlineRenameReplacementKind.ResolvedReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict, InlineRenameReplacementKind.ResolvedNonReferenceConflict => VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict, InlineRenameReplacementKind.UnresolvedConflict => VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict, InlineRenameReplacementKind.Complexified => VSTypeScriptInlineRenameReplacementKind.Complexified, _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } public static InlineRenameReplacementKind ConvertTo(VSTypeScriptInlineRenameReplacementKind kind) { return kind switch { VSTypeScriptInlineRenameReplacementKind.NoConflict => InlineRenameReplacementKind.NoConflict, VSTypeScriptInlineRenameReplacementKind.ResolvedReferenceConflict => InlineRenameReplacementKind.ResolvedReferenceConflict, VSTypeScriptInlineRenameReplacementKind.ResolvedNonReferenceConflict => InlineRenameReplacementKind.ResolvedNonReferenceConflict, VSTypeScriptInlineRenameReplacementKind.UnresolvedConflict => InlineRenameReplacementKind.UnresolvedConflict, VSTypeScriptInlineRenameReplacementKind.Complexified => InlineRenameReplacementKind.Complexified, _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./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.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 abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase { // if true suppresses params-array and default value: private readonly bool _suppressOptional; protected 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; } } #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 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.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 abstract class SourceClonedParameterSymbol : SourceParameterSymbolBase { // if true suppresses params-array and default value: private readonly bool _suppressOptional; protected 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; } } #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 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
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/CSharp/Test/Semantic/Semantics/SemanticErrorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// this place is dedicated to binding related error tests /// </summary> public class SemanticErrorTests : CompilingTestBase { #region "Targeted Error Tests - please arrange tests in the order of error code" [Fact] public void CS0019ERR_BadBinaryOps01() { var text = @" namespace x { public class b { public static void Main() { bool q = false; if (q == 1) { } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 9, Column = 17 }); } [Fact] public void CS0019ERR_BadBinaryOps02() { var text = @"using System; enum E { A, B, C } enum F { X = (E.A + E.B) * DayOfWeek.Monday } // no error class C { static void M(object o) { M((E.A + E.B) * DayOfWeek.Monday); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 8, Column = 12 }); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps03() { var text = @"delegate void MyDelegate1(ref int x, out float y); class Program { public void DelegatedMethod1(ref int x, out float y) { y = 1; } public void DelegatedMethod2(out int x, ref float y) { x = 1; } public void DelegatedMethod3(out int x, float y = 1) { x = 1; } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod1; md1 += mc.DelegatedMethod2; // Invalid md1 += mc.DelegatedMethod3; // Invalid md1 -= mc.DelegatedMethod1; md1 -= mc.DelegatedMethod2; // Invalid md1 -= mc.DelegatedMethod3; // Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (21,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (22,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1"), // (24,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (25,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1") ); } // Method List to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps04() { var text = @"using System; delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; boo goo1 = new boo(abc.far); boo[] arrfoo = { p.bar, abc.far }; goo += arrfoo; // Invalid goo -= arrfoo; // Invalid goo += new boo[] { p.bar, abc.far }; // Invalid goo -= new boo[] { p.bar, abc.far }; // Invalid goo += Delegate.Combine(arrfoo); // Invalid goo += Delegate.Combine(goo, goo1); // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (16,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (17,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (18,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (19,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (20,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(arrfoo); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(arrfoo)").WithArguments("System.Delegate", "boo"), // (21,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(goo, goo1); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(goo, goo1)").WithArguments("System.Delegate", "boo") ); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps05() { var text = @"public delegate double MyDelegate1(ref int integerPortion, out float fraction); public delegate double MyDelegate2(ref int integerPortion, out float fraction); class C { static void Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; MyDelegate2 md2 = null; md1 += md2; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0029: Cannot implicitly convert type 'MyDelegate2' to 'MyDelegate1' // md1 += md2; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "md2").WithArguments("MyDelegate2", "MyDelegate1") ); } // Anonymous method to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps06() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (7,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (8,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Lambda expression to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps07() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += (string x) => { };// Invalid goo -= (string x) => { };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (7,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (8,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Successive operator for addition and subtraction assignment [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps08() { var text = @"using System; delegate void boo(int x); class C { public void bar(int x) { Console.WriteLine("""", x); } static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { C p = new C(); boo goo = null; goo += p.bar + far;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far;// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (11,16): error CS0019: Operator '+' cannot be applied to operands of type 'method group' and 'method group' // goo += p.bar + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, "p.bar + far").WithArguments("+", "method group", "method group").WithLocation(11, 16), // (12,16): error CS0019: Operator '+' cannot be applied to operands of type 'lambda expression' and 'method group' // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"(x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far").WithArguments("+", "lambda expression", "method group").WithLocation(12, 16), // (12,70): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(12, 70), // (13,16): error CS0019: Operator '+' cannot be applied to operands of type 'anonymous method' and 'method group' // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far").WithArguments("+", "anonymous method", "method group").WithLocation(13, 16), // (13,83): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(13, 83) ); } // Removal or concatenation for the delegate on Variance [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps09() { var text = @"using System.Collections.Generic; delegate IList<int> Delegate1(List<int> x); delegate IEnumerable<int> Delegate2(IList<int> x); delegate IEnumerable<long> Delegate3(IList<long> x); class C { public static List<int> Method1(IList<int> x) { return null; } public static IList<long> Method1(IList<long> x) { return null; } static void Main(string[] args) { Delegate1 d1 = Method1; d1 += Method1; Delegate2 d2 = Method1; d2 += Method1; Delegate3 d3 = Method1; d1 += d2; // invalid d2 += d1; // invalid d2 += d3; // invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0029: Cannot implicitly convert type 'Delegate2' to 'Delegate1' // d1 += d2; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("Delegate2", "Delegate1"), // (26,15): error CS0029: Cannot implicitly convert type 'Delegate1' to 'Delegate2' // d2 += d1; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("Delegate1", "Delegate2"), // (27,15): error CS0029: Cannot implicitly convert type 'Delegate3' to 'Delegate2' // d2 += d3; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("Delegate3", "Delegate2") ); } // generic-delegate (goo<t>(...)) += non generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps10() { var text = @"delegate void boo<T>(T x); class C { public void bar(int x) { System.Console.WriteLine(""bar:{0}"", x); } public void bar1(string x) { System.Console.WriteLine(""bar1:{0}"", x); } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += p.bar;// OK goo += p.bar1;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo += (string x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid boo<string> goo1 = null; goo1 += p.bar;// Invalid goo1 += p.bar1;// OK goo1 += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo1 += (int x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo1 += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid goo1 += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += goo1;// Invalid goo1 += goo;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (12,18): error CS0123: No overload for 'bar1' matches delegate 'boo<int>' // goo += p.bar1;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar1").WithArguments("bar1", "boo<int>"), // (14,16): error CS1661: Cannot convert lambda expression to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(string x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<int>"), // (14,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (16,16): error CS1661: Cannot convert anonymous method to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<int>"), // (16,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (19,19): error CS0123: No overload for 'bar' matches delegate 'boo<string>' // goo1 += p.bar;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar").WithArguments("bar", "boo<string>"), // (22,17): error CS1661: Cannot convert lambda expression to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(int x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<string>"), // (22,22): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (23,17): error CS1661: Cannot convert anonymous method to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<string>"), // (23,31): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (25,16): error CS0029: Cannot implicitly convert type 'boo<string>' to 'boo<int>' // goo += goo1;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo1").WithArguments("boo<string>", "boo<int>"), // (26,17): error CS0029: Cannot implicitly convert type 'boo<int>' to 'boo<string>' // goo1 += goo;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo").WithArguments("boo<int>", "boo<string>") ); } // generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps11() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // non generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps12() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // distinguish '|' from '||' [WorkItem(540235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540235")] [Fact] public void CS0019ERR_BadBinaryOps13() { var text = @" class C { int a = 1 | 1; int b = 1 & 1; int c = 1 || 1; int d = 1 && 1; bool e = true | true; bool f = true & true; bool g = true || true; bool h = true && true; } "; CreateCompilation(text).VerifyDiagnostics( // (6,13): error CS0019: Operator '||' cannot be applied to operands of type 'int' and 'int' // int c = 1 || 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 || 1").WithArguments("||", "int", "int"), // (7,13): error CS0019: Operator '&&' cannot be applied to operands of type 'int' and 'int' // int d = 1 && 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 && 1").WithArguments("&&", "int", "int"), // (4,9): warning CS0414: The field 'C.a' is assigned but its value is never used // int a = 1 | 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C.a"), // (5,9): warning CS0414: The field 'C.b' is assigned but its value is never used // int b = 1 & 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("C.b"), // (9,10): warning CS0414: The field 'C.e' is assigned but its value is never used // bool e = true | true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("C.e"), // (10,10): warning CS0414: The field 'C.f' is assigned but its value is never used // bool f = true & true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f"), // (11,10): warning CS0414: The field 'C.g' is assigned but its value is never used // bool g = true || true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g"), // (12,10): warning CS0414: The field 'C.h' is assigned but its value is never used // bool h = true && true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "h").WithArguments("C.h")); } /// <summary> /// Conversion errors for Null Coalescing operator(??) /// </summary> [Fact] public void CS0019ERR_BadBinaryOps14() { var text = @" public class D { } public class Error { public int? NonNullableValueType_a(int a) { int? b = null; int? z = a ?? b; return z; } public int? NonNullableValueType_b(char ch) { char b = ch; int? z = null ?? b; return z; } public int NonNullableValueType_const_a(char ch) { char b = ch; int z = 10 ?? b; return z; } public D NoPossibleConversionError() { D b = new D(); Error a = null; D z = a ?? b; return z; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'int?' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "int", "int?"), // (13,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? b").WithArguments("??", "<null>", "char"), // (19,17): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "10 ?? b").WithArguments("??", "int", "char"), // (26,15): error CS0019: Operator '??' cannot be applied to operands of type 'Error' and 'D' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "Error", "D")); } [WorkItem(542115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542115")] [Fact] public void CS0019ERR_BadBinaryOps15() { var text = @"class C { static void M<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4, int i, C c) where T2 : class where T3 : struct where T4 : T1 { bool b; b = (t1 == t1); b = (t1 == t2); b = (t1 == t3); b = (t1 == t4); b = (t1 == i); b = (t1 == c); b = (t1 == null); b = (t2 == t1); b = (t2 == t2); b = (t2 == t3); b = (t2 == t4); b = (t2 == i); b = (t2 == c); b = (t2 == null); b = (t3 == t1); b = (t3 == t2); b = (t3 == t3); b = (t3 == t4); b = (t3 == i); b = (t3 == c); b = (t3 == null); b = (t4 != t1); b = (t4 != t2); b = (t4 != t3); b = (t4 != t4); b = (t4 != i); b = (t4 != c); b = (t4 != null); b = (i != t1); b = (i != t2); b = (i != t3); b = (i != t4); b = (i != i); b = (i != c); b = (i != null); b = (c != t1); b = (c != t2); b = (c != t3); b = (c != t4); b = (c != i); b = (c != c); b = (c != null); b = (null != t1); b = (null != t2); b = (null != t3); b = (null != t4); b = (null != i); b = (null != c); b = (null != null); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T1' // b = (t1 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t1").WithArguments("==", "T1", "T1"), // (10,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T2' // b = (t1 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t2").WithArguments("==", "T1", "T2"), // (11,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T3' // b = (t1 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t3").WithArguments("==", "T1", "T3"), // (12,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T4' // b = (t1 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t4").WithArguments("==", "T1", "T4"), // (13,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'int' // b = (t1 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == i").WithArguments("==", "T1", "int"), // (14,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'C' // b = (t1 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == c").WithArguments("==", "T1", "C"), // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T1' // b = (t2 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t1").WithArguments("==", "T2", "T1"), // (18,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T3' // b = (t2 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t3").WithArguments("==", "T2", "T3"), // (19,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T4' // b = (t2 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t4").WithArguments("==", "T2", "T4"), // (20,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'int' // b = (t2 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == i").WithArguments("==", "T2", "int"), // (23,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T1' // b = (t3 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t1").WithArguments("==", "T3", "T1"), // (24,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T2' // b = (t3 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t2").WithArguments("==", "T3", "T2"), // (25,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T3' // b = (t3 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t3").WithArguments("==", "T3", "T3"), // (26,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T4' // b = (t3 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t4").WithArguments("==", "T3", "T4"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'int' // b = (t3 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == i").WithArguments("==", "T3", "int"), // (28,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'C' // b = (t3 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == c").WithArguments("==", "T3", "C"), // (29,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and '<null>' // b = (t3 == null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == null").WithArguments("==", "T3", "<null>"), // (30,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T1' // b = (t4 != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t1").WithArguments("!=", "T4", "T1"), // (31,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T2' // b = (t4 != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t2").WithArguments("!=", "T4", "T2"), // (32,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T3' // b = (t4 != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t3").WithArguments("!=", "T4", "T3"), // (33,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T4' // b = (t4 != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t4").WithArguments("!=", "T4", "T4"), // (34,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'int' // b = (t4 != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != i").WithArguments("!=", "T4", "int"), // (35,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'C' // b = (t4 != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != c").WithArguments("!=", "T4", "C"), // (37,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T1' // b = (i != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t1").WithArguments("!=", "int", "T1"), // (38,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T2' // b = (i != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t2").WithArguments("!=", "int", "T2"), // (39,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T3' // b = (i != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t3").WithArguments("!=", "int", "T3"), // (40,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T4' // b = (i != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t4").WithArguments("!=", "int", "T4"), // (42,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'C' // b = (i != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != c").WithArguments("!=", "int", "C"), // (44,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T1' // b = (c != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t1").WithArguments("!=", "C", "T1"), // (46,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T3' // b = (c != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t3").WithArguments("!=", "C", "T3"), // (47,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T4' // b = (c != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t4").WithArguments("!=", "C", "T4"), // (48,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'int' // b = (c != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != i").WithArguments("!=", "C", "int"), // (53,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'T3' // b = (null != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != t3").WithArguments("!=", "<null>", "T3"), // (17,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (t2 == t2); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t2 == t2"), // (41,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (i != i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i != i"), // (43,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (i != null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?"), // (49,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (c != c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c != c"), // (55,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (null != i); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?")); } [Fact] public void CS0019ERR_BadBinaryOps16() { var text = @"class A { } class B : A { } interface I { } class C { static void M<T, U>(T t, U u, A a, B b, C c, I i) where T : A where U : B { bool x; x = (t == t); x = (t == u); x = (t == a); x = (t == b); x = (t == c); x = (t == i); x = (u == t); x = (u == u); x = (u == a); x = (u == b); x = (u == c); x = (u == i); x = (a == t); x = (a == u); x = (a == a); x = (a == b); x = (a == c); x = (a == i); x = (b == t); x = (b == u); x = (b == a); x = (b == b); x = (b == c); x = (b == i); x = (c == t); x = (c == u); x = (c == a); x = (c == b); x = (c == c); x = (c == i); x = (i == t); x = (i == u); x = (i == a); x = (i == b); x = (i == c); x = (i == i); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,14): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'C' // x = (t == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t == c").WithArguments("==", "T", "C"), // (21,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and 'C' // x = (u == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == c").WithArguments("==", "U", "C"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'A' and 'C' // x = (a == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "a == c").WithArguments("==", "A", "C"), // (33,14): error CS0019: Operator '==' cannot be applied to operands of type 'B' and 'C' // x = (b == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "b == c").WithArguments("==", "B", "C"), // (35,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'T' // x = (c == t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == t").WithArguments("==", "C", "T"), // (36,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'U' // x = (c == u); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == u").WithArguments("==", "C", "U"), // (37,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // x = (c == a); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == a").WithArguments("==", "C", "A"), // (38,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'B' // x = (c == b); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == b").WithArguments("==", "C", "B"), // (11,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (t == t); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (18,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (u == u); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "u == u"), // (25,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (a == a); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a"), // (32,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (b == b); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "b == b"), // (39,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (c == c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c == c"), // (46,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (i == i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i")); } [Fact] public void CS0019ERR_BadBinaryOps17() { var text = @"struct S { } abstract class A<T> { internal virtual void M<U>(U u) where U : T { bool b; b = (u == null); b = (null != u); } } class B : A<S> { internal override void M<U>(U u) { bool b; b = (u == null); b = (null != u); } }"; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == null").WithArguments("==", "U", "<null>").WithLocation(16, 14), // (17,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'U' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != u").WithArguments("!=", "<null>", "U").WithLocation(17, 14)); } [Fact] public void CS0020ERR_IntDivByZero() { var text = @" namespace x { public class b { public static int Main() { int s = 1 / 0; // CS0020 return s; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 21 } }); } [Fact] public void CS0020ERR_IntDivByZero_02() { var text = @" namespace x { public class b { public static void Main() { decimal x1 = 1.20M / 0; // CS0020 decimal x2 = 1.20M / decimal.Zero; // CS0020 decimal x3 = decimal.MaxValue / decimal.Zero; // CS0020 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 9, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 10, Column = 26 } }); } [Fact] public void CS0021ERR_BadIndexLHS() { var text = @"enum E { } class C { static void M<T>() { object o; o = M[0]; o = ((System.Action)null)[0]; o = ((dynamic)o)[0]; o = default(E)[0]; o = default(T)[0]; o = (new C())[0]; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,13): error CS0021: Cannot apply indexing with [] to an expression of type 'method group' Diagnostic(ErrorCode.ERR_BadIndexLHS, "M[0]").WithArguments("method group").WithLocation(7, 13), // (8,13): error CS0021: Cannot apply indexing with [] to an expression of type 'System.Action' Diagnostic(ErrorCode.ERR_BadIndexLHS, "((System.Action)null)[0]").WithArguments("System.Action").WithLocation(8, 13), // (10,13): error CS0021: Cannot apply indexing with [] to an expression of type 'E' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(E)[0]").WithArguments("E").WithLocation(10, 13), // (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'T' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(T)[0]").WithArguments("T").WithLocation(11, 13), // (12,13): error CS0021: Cannot apply indexing with [] to an expression of type 'C' Diagnostic(ErrorCode.ERR_BadIndexLHS, "(new C())[0]").WithArguments("C").WithLocation(12, 13)); } [Fact] public void CS0022ERR_BadIndexCount() { var text = @" namespace x { public class b { public static void Main() { int[,] a = new int[10,2] ; a[2] = 4; //bad index count in access } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIndexCount, Line = 9, Column = 25 } }); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount02() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount03() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2] { 1 }; //bad index count in size specifier - with initializer } } "; // NOTE: Dev10 just gives a parse error on '2' CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", ""), // (6,35): error CS0846: A nested array initializer is expected Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "1")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount04() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount05() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,] { { 1 } }; //bad index count in size specifier - with initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp1() { var text = @" namespace X { class C { object M() { object q = new object(); if (!q) // CS0023 { } object obj = -null; // CS0023 obj = !null; // CS0023 obj = ~null; // CS0023 obj++; // CS0023 --obj; // CS0023 return +null; // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '!' cannot be applied to operand of type 'object' // if (!q) // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!q").WithArguments("!", "object").WithLocation(9, 17), // (12,26): error CS8310: Operator '-' cannot be applied to operand '<null>' // object obj = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(12, 26), // (13,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // obj = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(13, 19), // (14,19): error CS8310: Operator '~' cannot be applied to operand '<null>' // obj = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(14, 19), // (16,13): error CS0023: Operator '++' cannot be applied to operand of type 'object' // obj++; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "obj++").WithArguments("++", "object").WithLocation(16, 13), // (17,13): error CS0023: Operator '--' cannot be applied to operand of type 'object' // --obj; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "--obj").WithArguments("--", "object").WithLocation(17, 13), // (18,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // return +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(18, 20) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp_Nullable() { var text = @" public class Test { public static void Main() { bool? b = !null; // CS0023 int? n = ~null; // CS0023 float? f = +null; // CS0023 long? u = -null; // CS0023 ++n; n--; --u; u++; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // bool? b = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(6, 19), // (7,18): error CS8310: Operator '~' cannot be applied to operand '<null>' // int? n = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(7, 18), // (8,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // float? f = +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(8, 20), // (9,19): error CS8310: Operator '-' cannot be applied to operand '<null>' // long? u = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(9, 19) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp2() { var text = @" namespace X { class C { void M() { System.Action f = M; f = +M; // CS0023 f = +(() => { }); // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '+' cannot be applied to operand of type 'method group' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+M").WithArguments("+", "method group"), // (10,17): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+(() => { })").WithArguments("+", "lambda expression")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidMissingInstanceMethod() { var text = @"class C { void M() { M().Goo(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidToString() { var text = @"class C { void M() { M().ToString(); //plausible, but still wrong } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] public void CS0023ERR_BadUnaryOp_null() { var text = @" class X { static void Main() { int x = null.Length; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Length").WithArguments(".", "<null>")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] public void CS0023ERR_BadUnaryOp_lambdaExpression() { var text = @" class X { static void Main() { System.Func<int, int> f = arg => { arg = 2; return arg; }.ToString(); var x = delegate { }.ToString(); } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadUnaryOp, "arg => { arg = 2; return arg; }.ToString").WithArguments(".", "lambda expression"), Diagnostic(ErrorCode.ERR_BadUnaryOp, "delegate { }.ToString").WithArguments(".", "anonymous method")); } [Fact] public void CS0026ERR_ThisInStaticMeth() { var text = @" public class MyClass { public static int i = 0; public static void Main() { // CS0026 this.i = this.i + 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 18 } }); } [Fact] public void CS0026ERR_ThisInStaticMeth_StaticConstructor() { var text = @" public class MyClass { int f; void M() { } int P { get; set; } static MyClass() { this.f = this.P; this.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (10,18): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (11,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")); } [Fact] public void CS0026ERR_ThisInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = this.ToString(); } static object FLD = this.ToString(); static object PROP { get { return this.ToString(); } } static object METHOD() { return this.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object FLD = this.ToString(); Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (6,28): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static CLS() { var x = this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (8,39): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object PROP { get { return this.ToString(); } } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (9,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object METHOD() { return this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS0027ERR_ThisInBadContext() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = this.Fun() + 1; // CS0027 public void Fun() { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 6, Column = 20 } }); } [Fact] public void CS0027ERR_ThisInBadContext_2() { var text = @" using System; [assembly: A(P = this.ToString())] class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0027: Keyword 'this' is not available in the current context // [assembly: A(P = this.ToString())] Diagnostic(ErrorCode.ERR_ThisInBadContext, "this")); } [Fact] public void CS0027ERR_ThisInBadContext_Interactive() { string text = @" int a; int b = a; int c = this.a; // 1 this.c = // 2 this.a; // 3 int prop { get { return 1; } set { this.a = 1;} } // 4 void goo() { this.goo(); // 5 this.a = // 6 this.b; // 7 object c = this; // 8 } this.prop = 1; // 9 class C { C() : base() { } void goo() { this.goo(); // OK } }"; var comp = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script) }); comp.VerifyDiagnostics( // (4,9): error CS0027: Keyword 'this' is not available in the current context // int c = this.a; // 1 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(4, 9), // (5,1): error CS0027: Keyword 'this' is not available in the current context // this.c = // 2 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(5, 1), // (6,5): error CS0027: Keyword 'this' is not available in the current context // this.a; // 3 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(6, 5), // (16,1): error CS0027: Keyword 'this' is not available in the current context // this.prop = 1; // 9 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(16, 1), // (7,36): error CS0027: Keyword 'this' is not available in the current context // int prop { get { return 1; } set { this.a = 1;} } // 4 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(7, 36), // (10,5): error CS0027: Keyword 'this' is not available in the current context // this.goo(); // 5 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(10, 5), // (11,5): error CS0027: Keyword 'this' is not available in the current context // this.a = // 6 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 5), // (12,9): error CS0027: Keyword 'this' is not available in the current context // this.b; // 7 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(12, 9), // (13,16): error CS0027: Keyword 'this' is not available in the current context // object c = this; // 8 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 16) ); } [Fact] public void CS0029ERR_NoImplicitConv01() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = 1; public string Fun() { return err1; } public static void Main() { MyClass c = new MyClass(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConv, Line = 11, Column = 20 } }); } [Fact] public void CS0029ERR_NoImplicitConv02() { var source = "enum E { A = new[] { 1, 2, 3 } }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0029: Cannot implicitly convert type 'int[]' to 'int' // enum E { A = new[] { 1, 2, 3 } } Diagnostic(ErrorCode.ERR_NoImplicitConv, "new[] { 1, 2, 3 }").WithArguments("int[]", "int").WithLocation(1, 14)); } [Fact] public void CS0029ERR_NoImplicitConv03() { var source = @"class C { static void M() { const C d = F(); } static D F() { return null; } } class D { } "; CreateCompilation(source).VerifyDiagnostics( // (5,21): error CS0029: Cannot implicitly convert type 'D' to 'C' // const C d = F(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "F()").WithArguments("D", "C").WithLocation(5, 21)); } [WorkItem(541719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541719")] [Fact] public void CS0029ERR_NoImplicitConv04() { var text = @"class C1 { public static void Main() { bool m = true; int[] arr = new int[m]; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type 'bool' to 'int' // int[] arr = new int[m]; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "m").WithArguments("bool", "int").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // return true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 23)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // object obj = true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void IntLiteral_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { var obj = true ? 0 : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'void' // var obj = true ? 0 : M2(); Diagnostic(ErrorCode.ERR_InvalidQM, "true ? 0 : M2()").WithArguments("int", "void").WithLocation(6, 19) ); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "true ? M2() : M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_DiscardAssignment() { string text = @" class C { void M1() { _ = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_Assignment() { string text = @" class C { void M1() { object obj = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_DiscardAssignment() { string text = @" class C { void M1() { _ = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.M1()' returns void, a return keyword must not be followed by an object expression // return true ? M2() : M2(); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.M1()").WithLocation(6, 9)); } [Fact] public void CS0030ERR_NoExplicitConv() { var text = @" namespace x { public class iii { public static iii operator ++(iii aa) { return (iii)0; // CS0030 } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: Cannot convert type 'int' to 'x.iii' // return (iii)0; // CS0030 Diagnostic(ErrorCode.ERR_NoExplicitConv, "(iii)0").WithArguments("int", "x.iii")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [WorkItem(920, "http://github.com/dotnet/roslyn/issues/920")] [Fact] public void CS0030ERR_NoExplicitConv02() { const string text = @" public class C { public static void Main() { decimal x = (decimal)double.PositiveInfinity; } }"; var diagnostics = CreateCompilation(text).GetDiagnostics(); var savedCurrentCulture = Thread.CurrentThread.CurrentCulture; var savedCurrentUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; try { diagnostics.Verify( // (6,21): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } finally { Thread.CurrentThread.CurrentCulture = savedCurrentCulture; Thread.CurrentThread.CurrentUICulture = savedCurrentUICulture; } } [Fact] public void CS0030ERR_NoExplicitConv_Foreach() { var text = @" public class Test { static void Main(string[] args) { int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } }; foreach (int outer in arr) { } // invalid } }"; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int[]", "int")); } [Fact] public void CS0031ERR_ConstOutOfRange01() { var text = @"public class a { int num = (int)2147483648M; //CS0031 } "; CreateCompilation(text).VerifyDiagnostics( // (3,15): error CS0031: Constant value '2147483648M' cannot be converted to a 'int' // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(int)2147483648M").WithArguments("2147483648M", "int"), // (3,9): warning CS0414: The field 'a.num' is assigned but its value is never used // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "num").WithArguments("a.num")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [Fact] public void CS0031ERR_ConstOutOfRange02() { var text = @" enum E : ushort { A = 10, B = -1 // CS0031 } enum F : sbyte { A = 0x7f, B = 0xf0, // CS0031 C, D = (A + 1) - 2, E = (A + 1), // CS0031 } class A { byte bt = 256; } "; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS0031: Constant value '-1' cannot be converted to a 'ushort' // B = -1 // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "-1").WithArguments("-1", "ushort").WithLocation(5, 9), // (10,9): error CS0031: Constant value '240' cannot be converted to a 'sbyte' // B = 0xf0, // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "0xf0").WithArguments("240", "sbyte").WithLocation(10, 9), // (13,10): error CS0031: Constant value '128' cannot be converted to a 'sbyte' // E = (A + 1), // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "A + 1").WithArguments("128", "sbyte").WithLocation(13, 10), // (17,15): error CS0031: Constant value '256' cannot be converted to a 'byte' // byte bt = 256; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "256").WithArguments("256", "byte").WithLocation(17, 15), // (17,10): warning CS0414: The field 'A.bt' is assigned but its value is never used // byte bt = 256; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "bt").WithArguments("A.bt").WithLocation(17, 10)); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked04() { // Confirm that we truncate the constant value before performing the range check var template = @"public class C { void M() { System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 1.0)); //CS0221 } } "; var integralTypes = new Type[] { typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), }; foreach (Type t in integralTypes) { DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(template.Replace("System.Int32", t.ToString()), new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); } } // Note that the errors for Int64 and UInt64 are not // exactly the same as for Int32, etc. above, but the // differences match the native compiler. [WorkItem(528715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528715")] [Fact] public void CS0221ERR_ConstOutOfRangeChecked05() { // Confirm that we truncate the constant value before performing the range check var text1 = @"public class C { void M() { System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 0.9)); System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 1.0)); System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text1, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text2 = @"public class C { void M() { System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 0.9)); System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text2, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text3 = @"class C { static void Main() { System.Console.WriteLine(long.MinValue); System.Console.WriteLine((long)(double)long.MinValue); } }"; CreateCompilation(text3).VerifyDiagnostics(); } [Fact] public void CS0034ERR_AmbigBinaryOps() { #region "Source" var text = @" public class A { // allows for the conversion of A object to int public static implicit operator int(A s) { return 0; } public static implicit operator string(A i) { return null; } } public class B { public static implicit operator int(B s) // one way to resolve this CS0034 is to make one conversion explicit // public static explicit operator int (B s) { return 0; } public static implicit operator string(B i) { return null; } public static implicit operator B(string i) { return null; } public static implicit operator B(int i) { return null; } } public class C { public static void Main() { A a = new A(); B b = new B(); b = b + a; // CS0034 // another way to resolve this CS0034 is to make a cast // b = b + (int)a; } } "; #endregion CreateCompilation(text).VerifyDiagnostics( // (47,13): error CS0034: Operator '+' is ambiguous on operands of type 'B' and 'A' // b = b + a; // CS0034 Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "b + a").WithArguments("+", "B", "A")); } [Fact] public void CS0035ERR_AmbigUnaryOp_RoslynCS0023() { var text = @" class MyClass { private int i; public MyClass(int i) { this.i = i; } public static implicit operator double(MyClass x) { return (double)x.i; } public static implicit operator decimal(MyClass x) { return (decimal)x.i; } } class MyClass2 { static void Main() { MyClass x = new MyClass(7); object o = -x; // CS0035 } }"; CreateCompilation(text).VerifyDiagnostics( // (27,20): error CS0035: Operator '-' is ambiguous on an operand of type 'MyClass' // object o = -x; // CS0035 Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "MyClass")); } [Fact] public void CS0037ERR_ValueCantBeNull01() { var source = @"enum E { } struct S { } class C { static void M() { int i; i = null; i = (int)null; E e; e = null; e = (E)null; S s; s = null; s = (S)null; X x; x = null; x = (X)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 13), // (9,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(int)null").WithArguments("int").WithLocation(9, 13), // (11,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("E").WithLocation(11, 13), // (12,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(E)null").WithArguments("E").WithLocation(12, 13), // (14,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("S").WithLocation(14, 13), // (15,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(S)null").WithArguments("S").WithLocation(15, 13), // (16,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(16, 9), // (18,14): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(18, 14)); } [Fact] public void CS0037ERR_ValueCantBeNull02() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = (T1)null; o = (T2)null; o = (T3)null; o = (T4)null; o = (T5)null; o = (T6)null; o = (T7)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0037: Cannot convert null to 'T1' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T1)null").WithArguments("T1").WithLocation(13, 13), // (15,17): error CS0037: Cannot convert null to 'T3' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T3)null").WithArguments("T3").WithLocation(15, 13), // (16,17): error CS0037: Cannot convert null to 'T4' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T4)null").WithArguments("T4").WithLocation(16, 13), // (17,17): error CS0037: Cannot convert null to 'T5' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T5)null").WithArguments("T5").WithLocation(17, 13), // (19,17): error CS0037: Cannot convert null to 'T7' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T7)null").WithArguments("T7").WithLocation(19, 13)); } [WorkItem(539589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539589")] [Fact] public void CS0037ERR_ValueCantBeNull03() { var text = @" class Program { enum MyEnum { Zero = 0, One = 1 } static int Main() { return Goo((MyEnum)null); } static int Goo(MyEnum x) { return 1; } } "; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(MyEnum)null").WithArguments("Program.MyEnum").WithLocation(12, 20)); } [Fact(), WorkItem(528875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528875")] public void CS0038ERR_WrongNestedThis() { var text = @" class OuterClass { public int count; // try the following line instead // public static int count; class InnerClass { void func() { // or, create an instance // OuterClass class_inst = new OuterClass(); // int count2 = class_inst.count; int count2 = count; // CS0038 } } public static void Main() { } }"; // Triage decided not to implement the more specific error (WrongNestedThis) and stick with ObjectRequired. var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode(649), ReportDiagnostic.Suppress } })); comp.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ObjectRequired, "count").WithArguments("OuterClass.count")); } [Fact] public void CS0039ERR_NoExplicitBuiltinConv01() { var text = @"class A { } class B: A { } class C: A { } class M { static void Main() { A a = new C(); B b = new B(); C c; // This is valid; there is a built-in reference // conversion from A to C. c = a as C; //The following generates CS0039; there is no // built-in reference conversion from B to C. c = b as C; // CS0039 } }"; CreateCompilation(text).VerifyDiagnostics( // (24,13): error CS0039: Cannot convert type 'B' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "b as C").WithArguments("B", "C").WithLocation(24, 13)); } [Fact, WorkItem(541142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541142")] public void CS0039ERR_NoExplicitBuiltinConv02() { var text = @"delegate void D(); class C { static void M(C c) { (F as D)(); (c.F as D)(); (G as D)(); } void F() { } static void G() { } }"; CreateCompilation(text).VerifyDiagnostics( // (6,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F as D").WithLocation(6, 10), // (7,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (c.F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.F as D").WithLocation(7, 10), // (8,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (G as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "G as D").WithLocation(8, 10)); } [Fact, WorkItem(542047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542047")] public void CS0039ERR_ConvTypeReferenceToObject() { var text = @"using System; class C { static void Main() { TypedReference a = new TypedReference(); object obj = a as object; //CS0039 } } "; CreateCompilation(text).VerifyDiagnostics( //(7,22): error CS0039: Cannot convert type 'System.TypedReference' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "a as object").WithArguments("System.TypedReference", "object").WithLocation(7, 22)); } [Fact] public void CS0069ERR_EventPropertyInInterface() { var text = @" interface I { event System.Action E1 { add; } event System.Action E2 { remove; } event System.Action E3 { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (4,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(4, 30), // (4,33): error CS0073: An add or remove accessor must have a body // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(4, 33), // (5,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 30), // (5,36): error CS0073: An add or remove accessor must have a body // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(5, 36), // (6,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 30), // (6,33): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 33), // (6,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 35), // (6,41): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 41), // (4,25): error CS0065: 'I.E1': event property must have both add and remove accessors // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I.E1").WithLocation(4, 25), // (5,25): error CS0065: 'I.E2': event property must have both add and remove accessors // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("I.E2").WithLocation(5, 25)); } [Fact] public void CS0070ERR_BadEventUsage() { var text = @" public delegate void EventHandler(); public class A { public event EventHandler Click; public static void OnClick() { EventHandler eh; A a = new A(); eh = a.Click; } public static void Main() { } } public class B { public int mf () { EventHandler eh = new EventHandler(A.OnClick); A a = new A(); eh = a.Click; // CS0070 // try the following line instead // a.Click += eh; return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsage, Line = 26, Column = 14 } }); } [Fact] public void CS0079ERR_BadEventUsageNoField() { var text = @" public delegate void MyEventHandler(); public class Class1 { private MyEventHandler _e; public event MyEventHandler Pow { add { _e += value; } remove { _e -= value; } } public void Handler() { } public void Fire() { if (_e != null) { Pow(); // CS0079 // try the following line instead // _e(); } } public static void Main() { Class1 p = new Class1(); p.Pow += new MyEventHandler(p.Handler); p._e(); p.Pow += new MyEventHandler(p.Handler); p._e(); p._e -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } p.Pow -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsageNoField, Line = 28, Column = 13 } }); } [WorkItem(538213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538213")] [Fact] public void CS0103ERR_NameNotInContext() { var text = @" class C { static void M() { IO.File.Exists(""test""); } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "IO").WithArguments("IO").WithLocation(6, 9)); } [WorkItem(542574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542574")] [Fact] public void CS0103ERR_NameNotInContextLambdaExtension() { var text = @"using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = sourceA.Join(sourceB, a => b, b => 5, (a, b) => a + b); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(9, 48)); } [Fact()] public void CS0103ERR_NameNotInContext_foreach() { var text = @"class C { static void Main() { foreach (var y in new[] {new {y = y }}){ } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(5, 43)); } [WorkItem(528780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528780")] [Fact] public void CS0103ERR_NameNotInContext_namedAndOptional() { var text = @"using System; class NamedExample { static void Main(string[] args) { } static int CalculateBMI(int weight, int height = weight) { return (weight * 703) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,54): error CS0103: The name 'weight' does not exist in the current context // static int CalculateBMI(int weight, int height = weight) Diagnostic(ErrorCode.ERR_NameNotInContext, "weight").WithArguments("weight").WithLocation(7, 54), // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1) ); } [Fact] public void CS0118ERR_BadSKknown() { CreateCompilation( @"public class TestType {} public class MyClass { public static int Main() { TestType myTest = new TestType(); bool b = myTest is myTest; return 1; } }", parseOptions: TestOptions.Regular6) .VerifyDiagnostics( // (7,22): error CS0118: 'myTest' is a 'variable' but is used like a 'type' Diagnostic(ErrorCode.ERR_BadSKknown, "myTest").WithArguments("myTest", "variable", "type")); } [Fact] public void CS0118ERR_BadSKknown_02() { CreateCompilation(@" using System; public class P { public static void Main(string[] args) { #pragma warning disable 219 Action<args> a = null; Action<a> b = null; } }") .VerifyDiagnostics( // (6,16): error CS0118: 'args' is a variable but is used like a type // Action<args> a = null; Diagnostic(ErrorCode.ERR_BadSKknown, "args").WithArguments("args", "variable", "type").WithLocation(6, 16), // (7,16): error CS0118: 'a' is a variable but is used like a type // Action<a> b = null; Diagnostic(ErrorCode.ERR_BadSKknown, "a").WithArguments("a", "variable", "type").WithLocation(7, 16)); } [Fact] public void CS0118ERR_BadSKknown_CheckedUnchecked() { string source = @" using System; class Program { static void Main() { var z = 1; (Console).WriteLine(); // error (System).Console.WriteLine(); // error checked(Console).WriteLine(); // error checked(System).Console.WriteLine(); // error checked(z).ToString(); // ok checked(typeof(Console)).ToString(); // ok checked(Console.WriteLine)(); // ok checked(z) = 1; // ok } } "; CreateCompilation(source).VerifyDiagnostics( // (10,4): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (11,10): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable"), // (12,17): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (13,17): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable")); } [WorkItem(542773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542773")] [Fact] public void CS0119ERR_BadSKunknown01_switch() { CreateCompilation( @"class A { public static void Main() { } void goo(color color1) { switch (color) { default: break; } } } enum color { blue, green } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadSKunknown, "color").WithArguments("color", "type")); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214"), WorkItem(528703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528703")] public void CS0119ERR_BadSKunknown01() { var source = @"class Test { public static void M() { int x = 0; x = (global::System.Int32) + x; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type")); } [Fact] public void CS0119ERR_BadSKunknown02() { var source = @"class A { internal static object F; internal static void M() { } } class B<T, U> where T : A { static void M(T t) { U.ReferenceEquals(T.F, null); T.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0119: 'T' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (10,9): error CS0119: 'U' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type parameter"), // (11,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(541203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541203")] [Fact] public void CS0119ERR_BadSKunknown_InThrowStmt() { CreateCompilation( @"class Test { public static void M() { throw System.Exception; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Exception").WithArguments("System.Exception", "type")); } [Fact] public void CS0110ERR_CircConstValue01() { var source = @"namespace x { public class C { const int x = 1; const int a = x + b; const int b = x + c; const int c = x + d; const int d = x + e; const int e = x + a; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0110: The evaluation of the constant value for 'x.C.a' involves a circular definition // const int a = x + b; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("x.C.a").WithLocation(7, 19)); } [Fact] public void CS0110ERR_CircConstValue02() { var source = @"enum E { A = B, B = A } enum F { X, Y = Y } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B = A } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10), // (2,13): error CS0110: The evaluation of the constant value for 'F.Y' involves a circular definition // enum F { X, Y = Y } Diagnostic(ErrorCode.ERR_CircConstValue, "Y").WithArguments("F.Y").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue03() { var source = @"enum E { A, B = A } // no error enum F { W, X = Z, Y, Z } "; CreateCompilation(source).VerifyDiagnostics( // (2,13): error CS0110: The evaluation of the constant value for 'F.X' involves a circular definition // enum F { W, X = Z, Y, Z } Diagnostic(ErrorCode.ERR_CircConstValue, "X").WithArguments("F.X").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue04() { var source = @"enum E { A = B, B } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10)); } [Fact] public void CS0110ERR_CircConstValue05() { var source = @"enum E { A = C, B = C, C } "; CreateCompilation(source).VerifyDiagnostics( // (1,17): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // enum E { A = C, B = C, C } Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(1, 17)); } [Fact] public void CS0110ERR_CircConstValue06() { var source = @"class C { private const int F = (int)E.B; enum E { A = F, B } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // private const int F = (int)E.B; Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 23)); } [Fact] public void CS0110ERR_CircConstValue07() { // Should report errors from other subexpressions // in addition to circular reference. var source = @"class C { const int F = (long)(F + F + G); } "; CreateCompilation(source).VerifyDiagnostics( // (3,34): error CS0103: The name 'G' does not exist in the current context // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_NameNotInContext, "G").WithArguments("G").WithLocation(3, 34), // (3,15): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 15)); } [Fact] public void CS0110ERR_CircConstValue08() { // Decimal constants are special (since they're not runtime constants). var source = @"class C { const decimal D = D; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.D' involves a circular definition // const decimal D = D; Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("C.D").WithLocation(3, 19)); } [Fact] public void CS0116ERR_NamespaceUnexpected_1() { var test = @" int x; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (2,5): warning CS0168: The variable 'x' is declared but never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(2, 5) ); } [Fact] public void CS0116ERR_NamespaceUnexpected_2() { var test = @" namespace x { using System; void Method(string str) // CS0116 { Console.WriteLine(str); } } int AIProp { get ; set ; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 10, Column = 5 }); } [Fact] public void CS0116ERR_NamespaceUnexpected_3() { var test = @" namespace ns1 { goto Labl; // Invalid const int x = 1; Lab1: const int y = 2; } "; // TODO (tomat): EOFUnexpected shouldn't be reported if we enable parsing global statements in namespaces DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, // (4,5): error CS1022: Type or namespace definition, or end-of-file expected // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // (4,14): error CS1022: Type or namespace definition, or end-of-file expected // (6,5): error CS0116: A namespace does not directly contain members such as fields or methods // (6,9): error CS1022: Type or namespace definition, or end-of-file expected // (5,15): error CS0116: A namespace does not directly contain members such as fields or methods // (7,15): error CS0116: A namespace does not directly contain members such as fields or methods new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 4, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 6, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 7, Column = 15 }); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_4() { var test = @" delegate int D(); D d = null; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = null; Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = null;").WithLocation(3, 1), // (3,3): warning CS0219: The variable 'd' is assigned but its value is never used // D d = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d").WithLocation(3, 3) ); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_5() { var test = @" delegate int D(); D d = {;} "; // In this case, CS0116 is suppressed because of the syntax errors CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = {;} Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = {;").WithLocation(3, 1), // (3,8): error CS1513: } expected Diagnostic(ErrorCode.ERR_RbraceExpected, ";"), // (3,9): error CS1022: Type or namespace definition, or end-of-file expected Diagnostic(ErrorCode.ERR_EOFExpected, "}"), // (3,7): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead. Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, "{")); } [WorkItem(539129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539129")] [Fact] public void CS0117ERR_NoSuchMember() { CreateCompilation( @"enum E { } class C { static void M() { C.F(E.A); C.P = C.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("C", "F"), Diagnostic(ErrorCode.ERR_NoSuchMember, "A").WithArguments("E", "A"), Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("C", "P"), Diagnostic(ErrorCode.ERR_NoSuchMember, "Q").WithArguments("C", "Q")); } [Fact] public void CS0120ERR_ObjectRequired01() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static void M() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired02() { CreateCompilation( @"using System; class Program { private readonly int v = 5; delegate int del(int i); static void Main(string[] args) { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(7), ""he"")); } }") .VerifyDiagnostics( // (9,41): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' Diagnostic(ErrorCode.ERR_ObjectRequired, "v").WithArguments("Program.v")); } [Fact] public void CS0120ERR_ObjectRequired03() { var source = @"delegate int boo(); interface I { int bar(); } public struct abc : I { public int bar() { System.Console.WriteLine(""bar""); return 0x01; } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; goo += new boo(I.bar); goo(); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()"), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p") ); CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()").WithLocation(16, 24), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p").WithLocation(14, 13) ); } [WorkItem(543950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543950")] [Fact] public void CS0120ERR_ObjectRequired04() { CreateCompilation( @"using System; class Program { static void Main(string[] args) { var f = new Func<string>(() => ToString()); var g = new Func<int>(() => GetHashCode()); } }") .VerifyDiagnostics( // (7,40): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // var f = new Func<string>(() => ToString()); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()"), // (8,37): error CS0120: An object reference is required for the non-static field, method, or property 'object.GetHashCode()' // var g = new Func<int>(() => GetHashCode()); Diagnostic(ErrorCode.ERR_ObjectRequired, "GetHashCode").WithArguments("object.GetHashCode()") ); } [Fact] public void CS0120ERR_ObjectRequired_ConstructorInitializer() { CreateCompilation( @"class B { public B(params int[] p) { } } class C : B { int instanceField; static int staticField; int InstanceProperty { get; set; } static int StaticProperty { get; set; } int InstanceMethod() { return 0; } static int StaticMethod() { return 0; } C(int param) : base( param, instanceField, //CS0120 staticField, InstanceProperty, //CS0120 StaticProperty, InstanceMethod(), //CS0120 StaticMethod(), this.instanceField, //CS0027 C.staticField, this.InstanceProperty, //CS0027 C.StaticProperty, this.InstanceMethod(), //CS0027 C.StaticMethod()) { } } ") .VerifyDiagnostics( // (19,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.instanceField' // instanceField, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "instanceField").WithArguments("C.instanceField").WithLocation(19, 9), // (21,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceProperty' // InstanceProperty, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceProperty").WithArguments("C.InstanceProperty").WithLocation(21, 9), // (23,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceMethod()' // InstanceMethod(), //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceMethod").WithArguments("C.InstanceMethod()").WithLocation(23, 9), // (25,9): error CS0027: Keyword 'this' is not available in the current context // this.instanceField, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(25, 9), // (27,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceProperty, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 9), // (29,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceMethod(), //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(29, 9), // (8,9): warning CS0649: Field 'C.instanceField' is never assigned to, and will always have its default value 0 // int instanceField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceField").WithArguments("C.instanceField", "0").WithLocation(8, 9), // (9,16): warning CS0649: Field 'C.staticField' is never assigned to, and will always have its default value 0 // static int staticField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticField").WithArguments("C.staticField", "0").WithLocation(9, 16)); } [Fact] public void CS0120ERR_ObjectRequired_StaticConstructor() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static C() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired_NestedClass() { CreateCompilation( @" class C { object field; object Property { get; set; } void Method() { } class D { object field2; object Property2 { get; set; } public void Goo() { object f = field; object p = Property; Method(); } public static void Bar() { object f1 = field; object p1 = Property; Method(); object f2 = field2; object p2 = Property2; Goo(); } } class E : C { public void Goo() { object f3 = field; object p3 = Property; Method(); } } }") .VerifyDiagnostics( // (15,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (17,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (22,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f1 = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (23,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p1 = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (24,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (26,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.field2' // object f2 = field2; Diagnostic(ErrorCode.ERR_ObjectRequired, "field2").WithArguments("C.D.field2"), // (27,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Property2' // object p2 = Property2; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property2").WithArguments("C.D.Property2"), // (28,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Goo()' // Goo(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Goo").WithArguments("C.D.Goo()"), // (4,12): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null"), // (10,16): warning CS0649: Field 'C.D.field2' is never assigned to, and will always have its default value null // object field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field2").WithArguments("C.D.field2", "null")); } [Fact, WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] public void CS0120ERR_ObjectRequired_Attribute() { var text = @" using System.ComponentModel; enum ProtectionLevel { Privacy = 0 } class F { [DefaultValue(Prop.Privacy)] // CS0120 ProtectionLevel Prop { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0120: An object reference is required for the non-static field, method, or property 'F.Prop' // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "Prop").WithArguments("F.Prop"), // (9,17): error CS0176: Member 'ProtectionLevel.Privacy' cannot be accessed with an instance reference; qualify it with a type name instead // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Prop.Privacy").WithArguments("ProtectionLevel.Privacy") // Extra In Roslyn ); } [Fact] public void CS0121ERR_AmbigCall() { var text = @" public class C { void f(int i, double d) { } void f(double d, int i) { } public static void Main() { new C().f(1, 1); // CS0121 } }"; CreateCompilation(text).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.f(int, double)' and 'C.f(double, int)' // new C().f(1, 1); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("C.f(int, double)", "C.f(double, int)") ); } [WorkItem(539817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539817")] [Fact] public void CS0122ERR_BadAccess() { var text = @" class Base { private class P { int X; } } class Test : Base { void M() { object o = (P p) => 0; int x = P.X; int y = (P)null; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,21): error CS0122: 'Base.P' is inaccessible due to its protection level // object o = (P p) => 0; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (12,17): error CS0122: 'Base.P' is inaccessible due to its protection level // int x = P.X; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (13,18): error CS0122: 'Base.P' is inaccessible due to its protection level // int y = (P)null; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (4,27): warning CS0169: The field 'Base.P.X' is never used // private class P { int X; } Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("Base.P.X")); } [WorkItem(537683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537683")] [Fact] public void CS0122ERR_BadAccess02() { var text = @"public class Outer { private class base1 { } } public class MyClass : Outer.base1 { } "; var comp = CreateCompilation(text); var type1 = comp.SourceModule.GlobalNamespace.GetMembers("MyClass").Single() as NamedTypeSymbol; var b = type1.BaseType(); var errs = comp.GetDiagnostics(); Assert.Equal(1, errs.Count()); Assert.Equal(122, errs.First().Code); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess03() { var text = @" class C1 { private C1() { } } class C2 { protected C2() { } private C2(short x) {} } class C3 : C2 { C3() : base(3) {} // CS0122 } class Test { public static int Main() { C1 c1 = new C1(); // CS0122 C2 c2 = new C2(); // CS0122 return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,12): error CS0122: 'C2.C2(short)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("C2.C2(short)"), // (21,21): error CS0122: 'C1.C1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C1").WithArguments("C1.C1()"), // (22,21): error CS0122: 'C2.C2()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C2").WithArguments("C2.C2()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [WorkItem(540336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540336")] [Fact] public void CS0122ERR_BadAccess04() { var text = @" class A { protected class ProtectedClass { } public class B : I<ProtectedClass> { } } interface I<T> { } class Error { static void Goo<T>(I<T> i) { } static void Main() { Goo(new A.B()); } } "; var tree = Parse(text); var compilation = CreateCompilation(tree); var model = compilation.GetSemanticModel(tree); var compilationUnit = tree.GetCompilationUnitRoot(); var classError = (TypeDeclarationSyntax)compilationUnit.Members[2]; var mainMethod = (MethodDeclarationSyntax)classError.Members[1]; var callStmt = (ExpressionStatementSyntax)mainMethod.Body.Statements[0]; var callExpr = callStmt.Expression; var callPosition = callExpr.SpanStart; var boundCall = model.GetSpeculativeSymbolInfo(callPosition, callExpr, SpeculativeBindingOption.BindAsExpression); Assert.Null(boundCall.Symbol); Assert.Equal(1, boundCall.CandidateSymbols.Length); Assert.Equal(CandidateReason.OverloadResolutionFailure, boundCall.CandidateReason); var constructedMethodSymbol = (IMethodSymbol)(boundCall.CandidateSymbols[0]); Assert.Equal("void Error.Goo<A.ProtectedClass>(I<A.ProtectedClass> i)", constructedMethodSymbol.ToTestDisplayString()); var typeArgSymbol = constructedMethodSymbol.TypeArguments.Single(); Assert.Equal("A.ProtectedClass", typeArgSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Protected inner class is inaccessible"); var paramTypeSymbol = constructedMethodSymbol.Parameters.Single().Type; Assert.Equal("I<A.ProtectedClass>", paramTypeSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Type should be inaccessible since type argument is inaccessible"); // The original test attempted to verify that "Error.Goo<A.ProtectedClass>" is an // inaccessible method when inside Error.Main. The C# specification nowhere gives // a special rule for constructed generic methods; the accessibility domain of // a method depends only on its declared accessibility and the declared accessibility // of its containing type. // // We should decide whether the answer to "is this method accessible in Main?" is // yes or no, and if no, change the implementation of IsAccessible accordingly. // // Assert.False(model.IsAccessible(callPosition, constructedMethodSymbol), "Method should be inaccessible since parameter type is inaccessible"); compilation.VerifyDiagnostics( // (16,9): error CS0122: 'Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess05() { var text = @" class Base { private Base() { } } class Derived : Base { private Derived() : this(1) { } //fine: can see own private members private Derived(int x) : base() { } //CS0122: cannot see base private members } "; CreateCompilation(text).VerifyDiagnostics( // (10,30): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess06() { var text = @" class Base { private Base() { } //private, but a match public Base(int x) { } //public, but not a match } class Derived : Base { private Derived() { } //implicit constructor initializer } "; CreateCompilation(text).VerifyDiagnostics( // (10,13): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()")); } [Fact] public void CS0123ERR_MethDelegateMismatch() { var text = @" delegate void D(); delegate void D2(int i); public class C { public static void f(int i) { } public static void Main() { D d = new D(f); // CS0123 D2 d2 = new D2(f); // OK } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethDelegateMismatch, Line = 11, Column = 15 } }); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [Fact] public void CS0123ERR_MethDelegateMismatch_01() { var text = @" delegate void boo(short x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo goo = null; goo += far<int>;// Invalid goo += far<short>;// OK } }"; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'C.far<int>(int)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<int>").WithArguments("C.far<int>(int)", "boo")); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [WorkItem(540053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540053")] [Fact] public void CS0123ERR_MethDelegateMismatch_02() { var text = @" delegate void boo(short x); class C<T> { public static void far(T x) { } public static void par<U>(U x) { System.Console.WriteLine(""par""); } public static boo goo = null; } class D { static void Main(string[] args) { C<long> p = new C<long>(); C<long>.goo += C<long>.far; C<long>.goo += C<long>.par<byte>; C<long>.goo(byte.MaxValue); C<long>.goo(long.MaxValue); C<short>.goo(long.MaxValue); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,24): error CS0123: No overload for 'C<long>.far(long)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "C<long>.far").WithArguments("C<long>.far(long)", "boo").WithLocation(15, 24), // (16,32): error CS0123: No overload for 'par' matches delegate 'boo' // C<long>.goo += C<long>.par<byte>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "par<byte>").WithArguments("par", "boo").WithLocation(16, 32), // (18,21): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(18, 21), // (19,22): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(19, 22) ); } [Fact] public void CS0123ERR_MethDelegateMismatch_DelegateVariance() { var text = @" delegate TOut D<out TOut, in TIn>(TIn p); class A { } class B : A { } class C : B { } class Test { static void Main() { D<B, B> d; d = F1; //CS0407 d = F2; //CS0407 d = F3; //CS0123 d = F4; d = F5; d = F6; //CS0123 d = F7; d = F8; d = F9; //CS0123 } static A F1(A p) { return null; } static A F2(B p) { return null; } static A F3(C p) { return null; } static B F4(A p) { return null; } static B F5(B p) { return null; } static B F6(C p) { return null; } static C F7(A p) { return null; } static C F8(B p) { return null; } static C F9(C p) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (13,13): error CS0407: 'A Test.F1(A)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F1").WithArguments("Test.F1(A)", "A"), // (14,13): error CS0407: 'A Test.F2(B)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F2").WithArguments("Test.F2(B)", "A"), // (15,13): error CS0123: No overload for 'F3' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F3").WithArguments("F3", "D<B, B>"), // (18,13): error CS0123: No overload for 'F6' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F6").WithArguments("F6", "D<B, B>"), // (21,13): error CS0123: No overload for 'F9' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F9").WithArguments("F9", "D<B, B>")); } [Fact] public void CS0126ERR_RetObjectRequired() { var source = @"namespace N { class C { object F() { return; } X G() { return; } C P { get { return; } } Y Q { get { return; } } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // X G() { return; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 9), // (8,9): error CS0246: The type or namespace name 'Y' could not be found (are you missing a using directive or an assembly reference?) // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Y").WithArguments("Y").WithLocation(8, 9), // (5,22): error CS0126: An object of a type convertible to 'object' is required // object F() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(5, 22), // (6,17): error CS0126: An object of a type convertible to 'X' is required // X G() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("X").WithLocation(6, 17), // (7,21): error CS0126: An object of a type convertible to 'C' is required // C P { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("N.C").WithLocation(7, 21), // (8,21): error CS0126: An object of a type convertible to 'Y' is required // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("Y").WithLocation(8, 21)); } [WorkItem(540115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540115")] [Fact] public void CS0126ERR_RetObjectRequired_02() { var source = @"namespace Test { public delegate object D(); public class TestClass { public static int Test(D src) { src(); return 0; } } public class MainClass { public static int Main() { return TestClass.Test(delegate() { return; }); // The native compiler produces two errors for this code: // // CS0126: An object of a type convertible to 'object' is required // // CS1662: Cannot convert anonymous method to delegate type // 'Test.D' because some of the return types in the block are not implicitly // convertible to the delegate return type // // This is not great; the first error is right, but does not tell us anything about // the fact that overload resolution has failed on the first argument. The second // error is actually incorrect; it is not that 'some of the return types are incorrect', // it is that some of the returns do not return anything in the first place! There's // no 'type' to get wrong. // // I would like Roslyn to give two errors: // // CS1503: Argument 1: cannot convert from 'anonymous method' to 'Test.D' // CS0126: An object of a type convertible to 'object' is required // // Neal Gafter says: I'd like one error instead of two. There is an error inside the // body of the lambda. It is enough to report that specific error. This is consistent // with our design guideline to suppress errors higher in the tree when it is caused // by an error lower in the tree. } } } "; CreateCompilation(source).VerifyDiagnostics( // (18,48): error CS0126: An object of a type convertible to 'object' is required // return TestClass.Test(delegate() { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(18, 48)); } [Fact] public void CS0127ERR_RetNoObjectRequired() { var source = @"namespace MyNamespace { public class MyClass { public void F() { return 0; } // CS0127 public int P { get { return 0; } set { return 0; } // CS0127, set has an implicit void return type } } } "; CreateCompilation(source).VerifyDiagnostics( // (5,27): error CS0127: Since 'MyClass.F()' returns void, a return keyword must not be followed by an object expression // public void F() { return 0; } // CS0127 Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.F()").WithLocation(5, 27), // (9,19): error CS0127: Since 'MyClass.P.set' returns void, a return keyword must not be followed by an object expression // set { return 0; } // CS0127, set has an implicit void return type Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.P.set").WithLocation(9, 19)); } [Fact] public void CS0127ERR_RetNoObjectRequired_StaticConstructor() { string text = @" class C { static C() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.C()' returns void, a return keyword must not be followed by an object expression Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.C()")); } [Fact] public void CS0128ERR_LocalDuplicate() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { char i = 'a'; int i = 2; // CS0128 if (i == 2) {} } } }"; CreateCompilation(text). VerifyDiagnostics( // (9,14): error CS0128: A local variable or function named 'i' is already defined in this scope // int i = 2; // CS0128 Diagnostic(ErrorCode.ERR_LocalDuplicate, "i").WithArguments("i").WithLocation(9, 14), // (9,14): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 2; // CS0128 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(9, 14) ); } [Fact] public void CS0131ERR_AssgLvalueExpected01() { CreateCompilation( @"class C { int i = 0; int P { get; set; } int this[int x] { get { return x; } set { } } void M() { ++P = 1; // CS0131 ++i = 1; // CS0131 ++this[0] = 1; //CS0131 } } ") .VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++P"), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++i"), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++this[0]")); } [Fact] public void CS0131ERR_AssgLvalueExpected02() { var source = @"class C { const object NoObject = null; static void M() { const int i = 0; i += 1; 3 *= 1; (i + 1) -= 1; ""string"" = null; null = new object(); NoObject = ""string""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // i += 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i").WithLocation(7, 9), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // 3 *= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "3").WithLocation(8, 9), // (9,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // (i + 1) -= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i + 1").WithLocation(9, 10), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // "string" = null; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, @"""string""").WithLocation(10, 9), // (11,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // null = new object(); Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "null").WithLocation(11, 9), // (12,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // NoObject = "string"; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "NoObject").WithLocation(12, 9)); } /// <summary> /// Breaking change from Dev10. CS0131 is now reported for all value /// types, not just struct types. Specifically, CS0131 is now reported /// for type parameters constrained to "struct". (See also CS1612.) /// </summary> [WorkItem(528763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528763")] [Fact] public void CS0131ERR_AssgLvalueExpected03() { var source = @"struct S { public object P { get; set; } public object this[object index] { get { return null; } set { } } } interface I { object P { get; set; } object this[object index] { get; set; } } class C { static void M<T>() where T : struct, I { default(S).P = null; default(T).P = null; // Dev10: no error default(S)[0] = null; default(T)[0] = null; // Dev10: no error } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S).P").WithLocation(16, 9), // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T).P").WithLocation(17, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S)[0]").WithLocation(18, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T)[0]").WithLocation(19, 9)); } [WorkItem(538077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538077")] [Fact] public void CS0132ERR_StaticConstParam() { var text = @" class A { static A(int z) { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Parameters = new string[] { "A.A(int)" } } }); } [Fact] public void CS0133ERR_NotConstantExpression01() { var source = @"class MyClass { public const int a = b; //no error since b is declared const public const int b = c; //CS0133, c is not constant public static int c = 1; //change static to const to correct program } "; CreateCompilation(source).VerifyDiagnostics( // (4,25): error CS0133: The expression being assigned to 'MyClass.b' must be constant // public const int b = c; //CS0133, c is not constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "c").WithArguments("MyClass.b").WithLocation(4, 25)); } [Fact] public void CS0133ERR_NotConstantExpression02() { var source = @"enum E { X, Y = C.F(), Z = C.G() + 1, } class C { public static E F() { return E.X; } public static int G() { return 0; } } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'E' to 'int'. An explicit conversion exists (are you missing a cast?) // Y = C.F(), Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "C.F()").WithArguments("E", "int").WithLocation(4, 9), // (4,9): error CS0133: The expression being assigned to 'E.Y' must be constant // Y = C.F(), Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.F()").WithArguments("E.Y").WithLocation(4, 9), // (5,9): error CS0133: The expression being assigned to 'E.Z' must be constant // Z = C.G() + 1, Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.G() + 1").WithArguments("E.Z").WithLocation(5, 9)); } [Fact] public void CS0133ERR_NotConstantExpression03() { var source = @"class C { static void M() { int y = 1; const int x = 2 * y; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0133: The expression being assigned to 'x' must be constant // const int x = 2 * y; Diagnostic(ErrorCode.ERR_NotConstantExpression, "2 * y").WithArguments("x").WithLocation(6, 23)); } [Fact] public void CS0133ERR_NotConstantExpression04() { var source = @"class C { static void M() { const int x = x + x; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,27): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 27), // (5,23): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 23)); } [Fact] public void CS0135ERR_NameIllegallyOverrides() { // See NameCollisionTests.cs for commentary on this error. var text = @" public class MyClass2 { public static int i = 0; public static void Main() { { int i = 4; // CS0135: Roslyn reports this error here i++; } i = 0; // Native compiler reports the error here } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0135ERR_NameIllegallyOverrides02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static int x; static void Main() { int z = x; var y = from x in Enumerable.Range(1, 100) // CS1931 select x; } }").VerifyDiagnostics( // (6,16): warning CS0649: Field 'Test.x' is never assigned to, and will always have its default value 0 // static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Test.x", "0").WithLocation(6, 16) ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides01() { // See comments in NameCollisionTests for thoughts on this error. string text = @"class C { static void M(object x) { string x = null; // CS0136 string y = null; if (x != null) { int y = 0; // CS0136 M(y); } M(x); M(y); } object P { get { int value = 0; // no error return value; } set { int value = 0; // CS0136 M(value); } } static void N(int q) { System.Func<int, int> f = q=>q; // 0136 } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17), // (30,35): error CS0136: A local or parameter named 'q' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // System.Func<int, int> f = q=>q; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "q").WithArguments("q").WithLocation(30, 35)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { static void M(object o) { try { } catch (System.IO.IOException e) { M(e); } catch (System.Exception e) // Legal; the two 'e' variables are in non-overlapping declaration spaces { M(e); } try { } catch (System.Exception o) // CS0136: Illegal; the two 'o' variables are in overlapping declaration spaces. { M(o); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "o").WithArguments("o").WithLocation(19, 33)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides03() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { int field = 0; int property { get; set; } static public void Main() { int[] ints = new int[] { 1, 2, 3 }; string[] strings = new string[] { ""1"", ""2"", ""3"" }; int conflict = 1; System.Console.WriteLine(conflict); foreach (int field in ints) { } // Legal: local hides field but name is used consistently foreach (string property in strings) { } // Legal: local hides property but name is used consistently foreach (string conflict in strings) { } // 0136: local hides another local in an enclosing local declaration space. } } ") .VerifyDiagnostics( // (14,25): error CS0136: A local or parameter named 'conflict' cannot be declared in this // scope because that name is used in an enclosing local scope to define a local or parameter // foreach (string conflict in strings) { } // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "conflict").WithArguments("conflict").WithLocation(14, 25), // (3,9): warning CS0414: The field 'C.field' is assigned but its value is never used // int field = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field")); } [WorkItem(538045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538045")] [Fact] public void CS0139ERR_NoBreakOrCont() { var text = @" namespace x { public class a { public static void Main(bool b) { if (b) continue; // CS0139 else break; // CS0139 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 9, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 11, Column = 17 }}); } [WorkItem(542400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542400")] [Fact] public void CS0140ERR_DuplicateLabel() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { label1: int i = M(); label1: int j = M(); // CS0140, comment this line to resolve goto label1; } static int M() { return 0; } } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,10): error CS0140: The label 'label1' is a duplicate // label1: int j = M(); // CS0140, comment this line to resolve Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(9, 10) ); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_Attribute() { var text = @" using A; using B; using System; namespace A { class var { } class XAttribute : Attribute { } } namespace B { class var { } class XAttribute : Attribute { } class X : Attribute { } } class Xyzzy { [X] // 17.2 If an attribute class is found both with and without this suffix, an ambiguity is present and a compile-time error occurs. public static void Main(string[] args) { } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_var() { var text = @" using A; using B; namespace A { class var { } } namespace B { class var { } } class Xyzzy { public static void Main(string[] args) { var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (21,9): error CS0104: 'var' is an ambiguous reference between 'A.var' and 'B.var' // var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... Diagnostic(ErrorCode.ERR_AmbigContext, "var").WithArguments("var", "A.var", "B.var") ); } [Fact] public void CS0144ERR_NoNewAbstract() { var text = @" interface ii { } abstract class aa { } public class a { public static void Main() { ii xx = new ii(); // CS0144 ii yy = new ii(Error); // CS0144, CS0103 aa zz = new aa(); // CS0144 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 14, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 15, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 16, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 15, Column = 22 } }); } [WorkItem(539583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539583")] [Fact] public void CS0150ERR_ConstantExpected() { var test = @" class C { static void Main() { byte x = 1; int[] a1 = new int[x]; int[] a2 = new int[x] { 1 }; //CS0150 const sbyte y = 1; const short z = 2; int[] b1 = new int[y + z]; int[] b2 = new int[y + z] { 1, 2, 3 }; } } "; CreateCompilation(test).VerifyDiagnostics( // (8,28): error CS0150: A constant value is expected Diagnostic(ErrorCode.ERR_ConstantExpected, "x")); } [Fact()] public void CS0151ERR_IntegralTypeValueExpected() { var text = @" public class iii { public static implicit operator int (iii aa) { return 0; } public static implicit operator long (iii aa) { return 0; } public static void Main() { iii a = new iii(); switch (a) // CS0151, compiler cannot choose between int and long { case 1: break; } } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (18,15): error CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier. // switch (a) // CS0151, compiler cannot choose between int and long Diagnostic(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, "a").WithLocation(18, 15), // (20,15): error CS0029: Cannot implicitly convert type 'int' to 'iii' // case 1: Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "iii").WithLocation(20, 15) ); } [Fact] public void CS0152ERR_DuplicateCaseLabel() { var text = @" namespace x { public class a { public static void Main() { int i = 0; switch (i) { case 1: i++; return; case 1: // CS0152, two case 1 statements i++; return; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (16,13): error CS0152: The switch statement contains multiple cases with the label value '1' // case 1: // CS0152, two case 1 statements Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case 1:").WithArguments("1").WithLocation(16, 13) ); } [Fact] public void CS0153ERR_InvalidGotoCase() { var text = @" public class a { public static void Main() { goto case 5; // CS0153 } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,7): error CS0153: A goto case is only valid inside a switch statement // goto case 5; // CS0153 Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto case 5;").WithLocation(6, 7)); } [Fact] public void CS0153ERR_InvalidGotoCase_2() { var text = @" class Program { static void Main(string[] args) { string Fruit = ""Apple""; switch (Fruit) { case ""Banana"": break; default: break; } goto default; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS0153: A goto case is only valid inside a switch statement // goto default; Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto default;").WithLocation(14, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet01() { CreateCompilation( @"class C { static object P { set { } } static int Q { set { } } static void M(object o) { C.P = null; o = C.P; // CS0154 M(P); // CS0154 ++C.Q; // CS0154 } } ") .VerifyDiagnostics( // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.P").WithArguments("C.P"), // (9,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P"), // (10,11): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.Q").WithArguments("C.Q")); } [Fact] public void CS0154ERR_PropertyLacksGet02() { var source = @"class A { public virtual A P { get; set; } public object Q { set { } } } class B : A { public override A P { set { } } void M() { M(Q); // CS0154, no get method } static void M(B b) { object o = b.P; // no error o = b.Q; // CS0154, no get method b.P.Q = null; // no error o = b.P.Q; // CS0154, no get method } static void M(object o) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,11): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // M(Q); // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("A.Q").WithLocation(11, 11), // (16,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.Q").WithArguments("A.Q").WithLocation(16, 13), // (18,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.P.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P.Q").WithArguments("A.Q").WithLocation(18, 13)); } [Fact] public void CS0154ERR_PropertyLacksGet03() { var source = @"class C { int P { set { } } void M() { P += 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // P += 1; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(6, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet04() { var source = @"class C { object p; object P { set { p = P; } } } "; CreateCompilation(source).VerifyDiagnostics( // (4,26): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // object P { set { p = P; } } Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(4, 26)); } [Fact] public void CS0154ERR_PropertyLacksGet05() { CreateCompilation( @"class C { object P { set { } } static bool Q { set { } } void M() { object o = P as string; o = P ?? Q; o = (o != null) ? P : Q; o = !Q; } }") .VerifyDiagnostics( // (7,20): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(7, 20), // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(8, 13), // (8,18): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(8, 18), // (9,27): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(9, 27), // (9,31): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(9, 31), // (10,14): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(10, 14)); } [Fact] public void CS0154ERR_PropertyLacksGet06() { CreateCompilation( @"class C { int this[int x] { set { } } void M(int b) { b = this[0]; b = 1 + this[1]; M(this[2]); this[3]++; this[4] += 1; } }") .VerifyDiagnostics( // (6,13): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[0]").WithArguments("C.this[int]"), // (7,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[1]").WithArguments("C.this[int]"), // (8,11): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[2]").WithArguments("C.this[int]"), // (9,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[3]").WithArguments("C.this[int]"), // (10,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[4]").WithArguments("C.this[int]")); } [Fact] public void CS0154ERR_PropertyLacksGet07() { var source1 = @"public class A { public virtual object P { private get { return null; } set { } } } public class B : A { public override object P { set { } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,17): error CS0154: The property or indexer 'B.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P").WithArguments("B.P").WithLocation(5, 17)); } [Fact] public void CS0155ERR_BadExceptionType() { var text = @"interface IA { } interface IB : IA { } struct S { } class C { static void M() { try { } catch (object) { } catch (System.Exception) { } catch (System.DateTime) { } catch (System.Int32) { } catch (IA) { } catch (IB) { } catch (S) { } catch (S) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExceptionType, "object").WithLocation(9, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.Exception").WithArguments("object").WithLocation(10, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.DateTime").WithLocation(11, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.Int32").WithLocation(12, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IA").WithLocation(13, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IB").WithLocation(14, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(15, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(16, 16)); } [Fact] public void CS0155ERR_BadExceptionType_Null() { var text = @"class C { static readonly bool False = false; const string T = null; static void M(object o) { const string s = null; if (False) throw null; if (False) throw (string)null; //CS0155 if (False) throw s; //CS0155 if (False) throw T; //CS0155 } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw (string)null; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "(string)null").WithArguments("string", "System.Exception").WithLocation(10, 26), // (11,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw s; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "s").WithArguments("string", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw T; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "T").WithArguments("string", "System.Exception").WithLocation(12, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_FailingAs() { var text = @" class C { static readonly bool False = false; static void M(object o) { if (False) throw new C() as D; //CS0155, though always null } } class D : C { } "; CreateCompilation(text).VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'D' to 'System.Exception' // if (False) throw new C() as D; //CS0155, though always null Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C() as D").WithArguments("D", "System.Exception").WithLocation(8, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_TypeParameters() { var text = @"using System; class C { static readonly bool False = false; static void M<T, TC, TS, TE>(object o) where TC : class where TS : struct where TE : Exception, new() { if (False) throw default(T); //CS0155 if (False) throw default(TC); //CS0155 if (False) throw default(TS); //CS0155 if (False) throw default(TE); if (False) throw new TE(); } } "; CreateCompilation(text).VerifyDiagnostics( // (11,26): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception' // if (False) throw default(T); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(T)").WithArguments("T", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'TC' to 'System.Exception' // if (False) throw default(TC); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TC)").WithArguments("TC", "System.Exception").WithLocation(12, 26), // (13,26): error CS0029: Cannot implicitly convert type 'TS' to 'System.Exception' // if (False) throw default(TS); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TS)").WithArguments("TS", "System.Exception").WithLocation(13, 26) ); } [Fact()] public void CS0155ERR_BadExceptionType_UserDefinedConversions() { var text = @"using System; class C { static readonly bool False = false; static void M(object o) { if (False) throw new Implicit(); //CS0155 if (False) throw new Explicit(); //CS0155 if (False) throw (Exception)new Implicit(); if (False) throw (Exception)new Explicit(); } } class Implicit { public static implicit operator Exception(Implicit i) { return null; } } class Explicit { public static explicit operator Exception(Explicit i) { return null; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Implicit()"), // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Explicit()") ); CreateCompilation(text).VerifyDiagnostics( // (9,26): error CS0266: Cannot implicitly convert type 'Explicit' to 'System.Exception'. An explicit conversion exists (are you missing a cast?) // if (False) throw new Explicit(); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new Explicit()").WithArguments("Explicit", "System.Exception").WithLocation(9, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_Dynamic() { var text = @" class C { static readonly bool False = false; static void M(object o) { dynamic d = null; if (False) throw d; //CS0155 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (9,26): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "d")); CreateCompilation(text).VerifyDiagnostics(); // dynamic conversion to Exception } [WorkItem(542995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542995")] [Fact] public void CS0155ERR_BadExceptionType_Struct() { var text = @" public class Test { public static void Main(string[] args) { } private void Method() { try { } catch (s1 s) { } } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (12,16): error CS0155: The type caught or thrown must be derived from System.Exception // catch (s1 s) Diagnostic(ErrorCode.ERR_BadExceptionType, "s1"), // (12,19): warning CS0168: The variable 's' is declared but never used // catch (s1 s) Diagnostic(ErrorCode.WRN_UnreferencedVar, "s").WithArguments("s") ); } [Fact] public void CS0156ERR_BadEmptyThrow() { var text = @" using System; namespace x { public class b : Exception { } public class a { public static void Main() { try { throw; // CS0156 } catch(b) { throw; // this throw is valid } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEmptyThrow, Line = 16, Column = 13 } }); } [Fact] public void CS0156ERR_BadEmptyThrow_Nesting() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; //avoid unreachable code if (b) throw; //CS0156 try { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } catch { if (b) throw; //fine try { if (b) throw; //fine } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 try { if (b) throw; //CS0724 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 } } } finally { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (9,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (12,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (20,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (41,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (44,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (52,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [Fact] public void CS0156ERR_BadEmptyThrow_Lambdas() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; // avoid unreachable code System.Action a; a = () => { throw; }; //CS0156 try { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } catch { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } finally { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (13,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (16,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (24,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (32,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (35,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (43,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (51,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (54,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (62,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave01() { var text = @"class C { static int F; static void M() { if (F == 0) goto Before; else if (F == 1) goto After; Before: ; try { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto TryBlock; else if (F == 3) return; TryBlock: ; } catch (System.Exception) { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto CatchBlock; else if (F == 3) return; CatchBlock: ; } finally { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto FinallyBlock; else if (F == 3) return; FinallyBlock: ; } After: ; } }"; CreateCompilation(text).VerifyDiagnostics( // (41,17): error CS0157: Control cannot leave the body of a finally clause // goto Before; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (43,17): error CS0157: Control cannot leave the body of a finally clause // goto After; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (47,17): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return"), // (3,16): warning CS0649: Field 'C.F' is never assigned to, and will always have its default value 0 // static int F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "0") ); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave02() { var text = @"using System; class C { static void F(int i) { } static void M() { for (int i = 0; i < 10;) { if (i < 5) { try { F(i); } catch (Exception) { continue; } finally { break; } } else { try { F(i); } catch (Exception) { break; } finally { continue; } } } } }"; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadFinallyLeave, "break").WithLocation(15, 27), Diagnostic(ErrorCode.ERR_BadFinallyLeave, "continue").WithLocation(21, 27)); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave03() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; } catch { i = 2; } finally { i = 3; goto lab1; }// invalid lab1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (9,26): error CS0157: Control cannot leave the body of a finally clause // finally { i = 3; goto lab1; }// invalid Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (6,13): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i") ); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { goto lab1; lab1: { lab1: goto lab1; // CS0158 } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelShadow, Line = 11, Column = 13 } }); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow_02() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del p = x => { goto label1; label1: // invalid return x * x; }; label1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,9): error CS0158: The label 'label1' shadows another label by the same name in a contained scope // label1: // invalid Diagnostic(ErrorCode.ERR_LabelShadow, "label1").WithArguments("label1"), // (13,5): warning CS0164: This label has not been referenced // label1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1") ); } [WorkItem(539875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539875")] [Fact] public void CS0159ERR_LabelNotFound() { var text = @" public class Cls { public static void Main() { goto Label2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelNotFound, Line = 6, Column = 14 } }); } [WorkItem(528799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528799")] [Fact()] public void CS0159ERR_LabelNotFound_2() { var text = @" class Program { static void Main(string[] args) { int s = 23; switch (s) { case 21: break; case 23: goto default; } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,17): error CS0159: No such label 'default:' within the scope of the goto statement // goto default; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto default;").WithArguments("default:"), // (11,13): error CS8070: Control cannot fall out of switch from final case label ('case 23:') // case 23: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 23:").WithArguments("case 23:")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_3() { var text = @" class Program { static void Main(string[] args) { goto Label; } public static void Goo() { Label: ; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_4() { var text = @" class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Label: i++; } goto Label; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_5() { var text = @" class Program { static void Main(string[] args) { if (true) { Label1: goto Label2; } else { Label2: goto Label1; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label2").WithArguments("Label2"), Diagnostic(ErrorCode.ERR_LabelNotFound, "Label1").WithArguments("Label1"), Diagnostic(ErrorCode.WRN_UnreachableCode, "Label2"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label2")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_6() { var text = @" class Program { static void Main(string[] args) { { goto L; } { L: return; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_7() { var text = @" class Program { static void Main(string[] args) { int i = 3; if (true) { label1: goto label3; if (!false) { label2: goto label5; if (i > 2) { label3: goto label2; if (i == 3) { label4: if (i < 5) { label5: if (i == 4) { } else { System.Console.WriteLine(""a""); } } } } } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "label3").WithArguments("label3"), Diagnostic(ErrorCode.ERR_LabelNotFound, "label5").WithArguments("label5"), Diagnostic(ErrorCode.WRN_UnreachableCode, "if"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label4"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label5"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label3"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label4"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label5")); } [WorkItem(540818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540818")] [Fact] public void CS0159ERR_LabelNotFound_8() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; // invalid return x * x; }; label2: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,17): warning CS0162: Unreachable code detected // return x * x; Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), // (9,17): error CS0159: No such label 'label2' within the scope of the goto statement // goto label2; // invalid Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label2"), // (12,5): warning CS0164: This label has not been referenced // label2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2") ); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_9() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { goto innerLoop; foreach (char y in x) { innerLoop: return; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "innerLoop").WithArguments("innerLoop"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "innerLoop")); } [Fact] public void CS0160ERR_UnreachableCatch() { var text = @"using System; using System.IO; class A : Exception { } class B : A { } class C : IOException { } interface I { } class D : Exception, I { } class E : IOException, I { } class F<T> : Exception { } class Program { static void M() { try { } catch (A) { } catch (D) { } catch (E) { } catch (IOException) { } catch (C) { } catch (F<bool>) { } catch (F<int>) { } catch (Exception) { } catch (B) { } catch (StackOverflowException) { } catch (F<int>) { } catch (F<float>) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "C").WithArguments("System.IO.IOException").WithLocation(19, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(23, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "StackOverflowException").WithArguments("System.Exception").WithLocation(24, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<int>").WithArguments("F<int>").WithLocation(25, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<float>").WithArguments("System.Exception").WithLocation(26, 16)); } [Fact] public void CS0160ERR_UnreachableCatch_Filter1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { int a = 1; try { } catch when (a == 1) { } catch (Exception e) when (e.Message == null) { } catch (A) { } catch (B e) when (e.Message == null) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('A') // catch (B e) when (e.Message == null) { } Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(15, 16)); } [Fact] public void CS8359WRN_FilterIsConstantFalse_NonBoolean() { // Non-boolean constant filters are not considered for WRN_FilterIsConstant warnings. var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (1) { } catch (B) when (0) { } catch (B) when (""false"") { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (A) when (1) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool").WithLocation(11, 25), // (12,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (B) when (0) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "bool").WithLocation(12, 25), // (13,25): error CS0029: Cannot implicitly convert type 'string' to 'bool' // catch (B) when ("false") { } Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""false""").WithArguments("string", "bool").WithLocation(13, 25), // (14,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(14, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse2() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "(1+1)!=2").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } finally { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch1() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "(1+1)!=2").WithLocation(10, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (true) { } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (A) when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(11, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when (true) { } catch (A) { } catch when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 21), // (12,19): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 21)); } [Fact] public void CS7095WRN_FilterIsConstantTrue3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when ((1+1)==2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "(1+1)==2").WithLocation(10, 21)); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { Console.WriteLine(1); } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (13,13): warning CS0162: Unreachable code detected // Console.WriteLine(1); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(13, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition2() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (false) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7105: Filter expression is a constant 'false', consider removing the try-catch block // catch (Exception) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 33), // (12,13): warning CS0162: Unreachable code detected // Console.WriteLine(x); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(12, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition3() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (true) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (Exception) when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 33), // (12,31): error CS0165: Use of unassigned local variable 'x' // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(12, 31) ); } [Fact] public void CS0160ERR_UnreachableCatch_Dynamic() { string source = @" using System; public class EG<T> : Exception { } public class A { public void M1() { try { Goo(); } catch (EG<object>) { } catch (EG<dynamic>) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (17,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "EG<dynamic>").WithArguments("EG<object>")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter() { string source = @" using System; public class EA : Exception { } public class EB : EA { } public class A<T> where T : EB { public void M1() { try { Goo(); } catch (EA) { } catch (T) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (18,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EA') Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("EA")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic1() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<dynamic>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<dynamic>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<dynamic>")); } [Fact] public void TypeParameter_DynamicConversions() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { V v = default(V); U u = default(U); // implicit EG<dynamic> egd = v; // implicit egd = u; //explicit v = (V)egd; //explicit u = (U)egd; //implicit array V[] va = null; EG<dynamic>[] egda = va; // explicit array va = (V[])egda; } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic2() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<object>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<object>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<object>")); } [Fact] public void CS0161ERR_ReturnExpected() { var text = @" public class Test { public static int Main() // CS0161 { int i = 10; if (i < 10) { return i; } else { // uncomment the following line to resolve // return 1; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnExpected, Line = 4, Column = 22 } }); } [Fact] public void CS0163ERR_SwitchFallThrough() { var text = @" public class MyClass { public static void Main() { int i = 0; switch (i) // CS0163 { case 1: i++; // uncomment one of the following lines to resolve // return; // break; // goto case 3; case 2: i++; return; case 3: i = 0; return; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SwitchFallThrough, Line = 10, Column = 10 } }); } [Fact] public void CS0165ERR_UseDefViolation01() { var text = @" class MyClass { public int i; } class MyClass2 { public static void Main(string [] args) { int i, j; if (args[0] == ""test"") { i = 0; } /* // to resolve, either initialize the variables when declared // or provide for logic to initialize them, as follows: else { i = 1; } */ j = i; // CS0165, i might be uninitialized MyClass myClass; myClass.i = 0; // CS0165 // use new as follows // MyClass myClass = new MyClass(); // myClass.i = 0; i = j; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 26, Column = 11 } , new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 29, Column = 7 }}); } [Fact] public void CS0165ERR_UseDefViolation02() { CreateCompilation( @"class C { static void M(int m) { int v; for (int i = 0; i < m; ++i) { v = 0; } M(v); int w; for (; ; ) { w = 0; break; } M(w); for (int x; x < 1; ++x) { } for (int y; m < 1; ++y) { } for (int z; ; ) { M(z); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "v").WithArguments("v").WithLocation(10, 11), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(18, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(21, 30), Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(26, 15)); } [Fact] public void CS0165ERR_UseDefViolation03() { CreateCompilation( @"class C { static int F() { return 0; } static void M0() { int a, b, c, d; for (a = 1; (b = F()) < 2; c = 3) { d = 4; } if (a == 0) { } if (b == 0) { } if (c == 0) { } // Use of unassigned 'c' if (d == 0) { } // Use of unassigned 'd' } static void M1() { int x, y; for (x = 0; (y = x) < 10; ) { } if (y == 0) { } // no error } static void M2() { int x, y; for (x = 0; x < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M3() { int x, y; for (x = 0; x < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M4() { int x, y; for (y = x; (x = 0) < 10; ) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M5() { int x, y; for (; (x = 0) < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M6() { int x, y; for (; (x = 0) < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M7() { int x, y; for (y = x; F() < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M8() { int x, y; for (; (y = x) < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M9() { int x, y; for (; F() < 10; x = 0) { y = x; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M10() { int x, y; for (y = x; F() < 10; ) { x = 0; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M11() { int x, y; for (; F() < 10; y = x) { x = 0; } if (y == 0) { } // Use of unassigned 'y' } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(13, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(14, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(26, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(32, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(37, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(44, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(50, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(55, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(61, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(67, 39), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(68, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(73, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(80, 13)); } [Fact] public void CS0165ERR_UseDefViolation04() { CreateCompilation( @"class C { static int M() { int x, y, z; try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } return (x + y + z); } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(19, 21)); } [Fact] public void CS0165ERR_UseDefViolation05() { // This is a "negative" test case; we should *not* be producing a "use of unassigned // local variable" error here. In an earlier revision we were doing so because we were // losing the information about the first argument being "out" when the bad call node // was created. Later flow analysis then did not know that "x" need not be assigned // before it was used, and we'd produce a wrong error. CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { int x = N(out x, 123); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "N").WithArguments("N", "2")); } [WorkItem(540860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540860")] [Fact] public void CS0165ERR_UseDefViolation06() { // Should not generate "unassigned local variable" for struct. CreateCompilation( @"struct S { public void M() { } } class C { void M() { S s; s.M(); } }") .VerifyDiagnostics(); } [Fact] public void CS0165ERR_UseDefViolation07() { // Make sure flow analysis is hooked up for indexers CreateCompilation( @"struct S { public int this[int x] { get { return 0; } } } class C { public int this[int x] { get { return 0; } } } class Test { static void Main() { int unassigned1; int unassigned2; int sink; C c; sink = c[1]; //CS0165 c = new C(); sink = c[1]; //fine sink = c[unassigned1]; //CS0165 S s; sink = s[1]; //fine - struct with no fields s = new S(); sink = s[1]; //fine sink = s[unassigned2]; //CS0165 } }") .VerifyDiagnostics( // (18,16): error CS0165: Use of unassigned local variable 'c' Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (22,18): error CS0165: Use of unassigned local variable 'unassigned1' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned1").WithArguments("unassigned1"), // (29,18): error CS0165: Use of unassigned local variable 'unassigned2' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned2").WithArguments("unassigned2")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0170ERR_UseDefViolationField() { var text = @" public struct error { public int i; } public class MyClass { public static void Main() { error e; // uncomment the next line to resolve this error // e.i = 0; System.Console.WriteLine( e.i ); // CS0170 because //e.i was never assigned } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationField, Line = 14, Column = 33 } }); } [Fact] public void CS0171ERR_UnassignedThis() { var text = @" struct MyStruct { MyStruct(int initField) // CS0171 { // i = initField; // uncomment this line to resolve this error } public int i; } class MyClass { public static void Main() { MyStruct aStruct = new MyStruct(); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,4): error CS0171: Field 'MyStruct.i' must be fully assigned before control is returned to the caller // MyStruct(int initField) // CS0171 Diagnostic(ErrorCode.ERR_UnassignedThis, "MyStruct").WithArguments("MyStruct.i"), // (15,16): warning CS0219: The variable 'aStruct' is assigned but its value is never used // MyStruct aStruct = new MyStruct(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "aStruct").WithArguments("aStruct"), // (8,15): warning CS0649: Field 'MyStruct.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("MyStruct.i", "0") ); } [Fact] public void FieldAssignedInReferencedConstructor() { var text = @"struct S { private readonly object _x; S(object o) { _x = o; } S(object x, object y) : this(x ?? y) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); // No CS0171 for S._x } [Fact()] public void CS0172ERR_AmbigQM() { var text = @" public class Square { public class Circle { public static implicit operator Circle(Square aa) { return null; } public static implicit operator Square(Circle aa) { return null; } } public static void Main() { Circle aa = new Circle(); Square ii = new Square(); var o1 = (1 == 1) ? aa : ii; // CS0172 object o2 = (1 == 1) ? aa : ii; // CS8652 } }"; CreateCompilation(text, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (21,16): error CS0172: Type of conditional expression cannot be determined because 'Square.Circle' and 'Square' implicitly convert to one another // var o1 = (1 == 1) ? aa : ii; // CS0172 Diagnostic(ErrorCode.ERR_AmbigQM, "(1 == 1) ? aa : ii").WithArguments("Square.Circle", "Square").WithLocation(21, 16), // (22,19): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between 'Square.Circle' and 'Square'. To use a target-typed conversion, upgrade to language version 9.0 or greater. // object o2 = (1 == 1) ? aa : ii; // CS8652 Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, "(1 == 1) ? aa : ii").WithArguments("8.0", "Square.Circle", "Square", "9.0").WithLocation(22, 19) ); } [Fact] public void CS0173ERR_InvalidQM() { var text = @" public class C {} public class A {} public class MyClass { public static void F(bool b) { A a = new A(); C c = new C(); var o = b ? a : c; // CS0173 } public static void Main() { F(true); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,15): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C' // var o = b ? a : c; // CS0173 Diagnostic(ErrorCode.ERR_InvalidQM, "b ? a : c").WithArguments("A", "C").WithLocation(11, 15) ); } [WorkItem(528331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528331")] [Fact] public void CS0173ERR_InvalidQM_FuncCall() { var text = @" class Program { static void Main(string[] args) { var s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1); } }"; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1)").WithArguments("void").WithLocation(6, 13)); } [Fact] public void CS0173ERR_InvalidQM_GeneralType() { var text = @" class Program { static void Main(string[] args) { A<string> a = new A<string>(); A<int> b = new A<int>(); var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert } } class A<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A<string>' and 'A<int>' // var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert Diagnostic(ErrorCode.ERR_InvalidQM, "1 > 2 ? a : b").WithArguments("A<string>", "A<int>").WithLocation(8, 17) ); } [WorkItem(540902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540902")] [Fact] public void CS0173ERR_InvalidQM_foreach() { var text = @" public class Test { public static void Main() { S[] x = null; foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY { } C[] y= null; foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY { } } } struct S { } class C { } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'S[]' and 'int' // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "true ? x : 1").WithArguments("S[]", "int"), // (7,20): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), // (11,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'C[]' // foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "false ? 1 : y").WithArguments("int", "C[]") ); } // /// Scenarios? // [Fact] // public void CS0174ERR_NoBaseClass() // { // var text = @" // "; // CreateCompilationWithMscorlib(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoBaseClass, "?")); // } [WorkItem(543360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543360")] [Fact()] public void CS0175ERR_BaseIllegal() { var text = @" using System; class Base { public int TestInt = 0; } class MyClass : Base { public void BaseTest() { Console.WriteLine(base); // CS0175 base = 9; // CS0175 } } "; CreateCompilation(text).VerifyDiagnostics( // (11,27): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(12, 27), // (12,9): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(13, 9) ); } [WorkItem(528624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528624")] [Fact()] public void CS0175ERR_BaseIllegal_02() { var text = @" using System.Collections.Generic; class MyClass : List<int> { public void BaseTest() { var x = from i in base select i; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,27): error CS0175: Use of keyword 'base' is not valid in this context // var x = from i in base select i; Diagnostic(ErrorCode.ERR_BaseIllegal, "base") ); } [Fact] public void CS0176ERR_ObjectProhibited01() { var source = @" class A { class B { static void Method() { } void M() { this.Method(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,13): error CS0176: Member 'A.B.Method()' cannot be accessed with an instance reference; qualify it with a type name instead // this.Method(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Method").WithArguments("A.B.Method()").WithLocation(9, 13) ); } [Fact] public void CS0176ERR_ObjectProhibited02() { var source = @" class C { static object field; static object Property { get; set; } void M(C c) { Property = field; // no error C.Property = C.field; // no error this.field = this.Property; c.Property = c.field; } } "; CreateCompilation(source).VerifyDiagnostics( // (9,9): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.field").WithArguments("C.field"), // (9,22): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Property").WithArguments("C.Property"), // (10,9): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.Property").WithArguments("C.Property"), // (10,22): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.field").WithArguments("C.field") ); } [Fact] public void CS0176ERR_ObjectProhibited03() { var source = @"class A { internal static object F; } class B<T> where T : A { static void M(T t) { object q = t.F; t.ReferenceEquals(q, null); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,20): error CS0176: Member 'A.F' cannot be accessed with an instance reference; qualify it with a type name instead // object q = t.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.F").WithArguments("A.F").WithLocation(9, 20), // (10,9): error CS0176: Member 'object.ReferenceEquals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // t.ReferenceEquals(q, null); Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.ReferenceEquals").WithArguments("object.ReferenceEquals(object, object)").WithLocation(10, 9), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null").WithLocation(3, 28)); } [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited04() { var source = @" public delegate void D(); class Test { public event D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics( // (9,9): error CS0176: Member 'Delegate.CreateDelegate(Type, object, string)' cannot be accessed with an instance reference; qualify it with a type name instead // D.CreateDelegate(null, null, null); // CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "D.CreateDelegate").WithArguments("System.Delegate.CreateDelegate(System.Type, object, string)").WithLocation(9, 9) ); } // Identical to CS0176ERR_ObjectProhibited04, but with event keyword removed (i.e. field instead of field-like event). [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited05() { var source = @" public delegate void D(); class Test { public D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source).VerifyDiagnostics( // (5,14): warning CS0649: Field 'Test.D' is never assigned to, and will always have its default value null // public D D; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "D").WithArguments("Test.D", "null") ); } [Fact] public void CS0177ERR_ParamUnassigned01() { var text = @"class C { static void M(out int x, out int y, out int z) { try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("y").WithLocation(3, 17)); } [WorkItem(528243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528243")] [Fact] public void CS0177ERR_ParamUnassigned02() { var text = @"class C { static bool P { get { return false; } } static object M(out object x) { if (P) { object o = P ? M(out x) : null; return o; } return P ? null : M(out x); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return o; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return o;").WithArguments("x").WithLocation(9, 13), // (11,9): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return P ? null : M(out x); Diagnostic(ErrorCode.ERR_ParamUnassigned, "return P ? null : M(out x);").WithArguments("x").WithLocation(11, 9)); } [Fact] public void CS0185ERR_LockNeedsReference() { var text = @" public class MainClass { public static void Main () { lock (1) // CS0185 // try the following lines instead // MainClass x = new MainClass(); // lock(x) { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LockNeedsReference, Line = 6, Column = 15 } }); } [Fact] public void CS0186ERR_NullNotValid() { var text = @" using System.Collections; class MyClass { static void Main() { // Each of the following lines generates CS0186: foreach (int i in null) { } // CS0186 foreach (int i in (IEnumerable)null) { }; // CS0186 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 9, Column = 27 } , new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 10, Column = 27 }}); } [Fact] public void CS0186ERR_NullNotValid02() { var text = @" public class Test { public static void Main(string[] args) { foreach (var x in default(int[])) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NullNotValid, "default(int[])")); } [WorkItem(540983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540983")] [Fact] public void CS0188ERR_UseDefViolationThis() { var text = @" namespace MyNamespace { class MyClass { struct S { public int a; void Goo() { } S(int i) { // a = i; Goo(); // CS0188 } } public static void Main() { } } }"; CreateCompilation(text). VerifyDiagnostics( // (17,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(); // CS0188 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this"), // (8,24): warning CS0649: Field 'MyNamespace.MyClass.S.a' is never assigned to, and will always have its default value 0 // public int a; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("MyNamespace.MyClass.S.a", "0")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ImplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "F").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ExplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = this.F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "this.F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ImplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { /*this.*/ Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,19): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Add").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ExplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { this.Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact] public void CS0190ERR_ArgsInvalid() { string source = @" using System; public class C { static void M(__arglist) { ArgIterator ai = new ArgIterator(__arglist); } static void Main() { M(__arglist); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (11,7): error CS0190: The __arglist construct is valid only within a variable argument method // M(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda01() { // Note that the native compiler does *not* produce an error when you illegally // use __arglist inside a lambda, oddly enough. Roslyn does. string source = @" using System; using System.Linq; public class C { delegate int D(RuntimeArgumentHandle r); static void M(__arglist) { D f = null; f = x=>f(__arglist); f = delegate { return f(__arglist); }; var q = from x in new int[10] select f(__arglist); } static void Main() { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (10,14): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = x=>f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (11,29): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = delegate { return f(__arglist); }; Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (12,44): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // var q = from x in new int[10] select f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda02() { string source = @" using System; public class C { static void M(__arglist) { RuntimeArgumentHandle h = __arglist; Action action = ()=> { RuntimeArgumentHandle h2 = h; // Bad use of h ArgIterator args1 = new ArgIterator(h); // Bad use of h RuntimeArgumentHandle h3 = h2; // no error; does not create field ArgIterator args2 = new ArgIterator(h2); // no error; does not create field }; } static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyEmitDiagnostics( // (10,34): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // RuntimeArgumentHandle h2 = h; // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle"), // (11,43): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // ArgIterator args1 = new ArgIterator(h); // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle")); } [Fact] public void CS4013ERR_SpecialByRefInLambda03() { string source = @" using System; using System.Collections.Generic; public class C { static void N(RuntimeArgumentHandle x) {} static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field { N(h1); yield return 1; RuntimeArgumentHandle h2 = default(RuntimeArgumentHandle); yield return 2; N(h2); // Error: hoisted to field yield return 3; RuntimeArgumentHandle h3 = default(RuntimeArgumentHandle); N(h3); // No error; we don't need to hoist this one to a field } static void Main() { } }"; CreateCompilation(source).Emit(new System.IO.MemoryStream()).Diagnostics .Verify( // (7,51): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h1").WithArguments("System.RuntimeArgumentHandle"), // (13,7): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // N(h2); // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h2").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(538008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538008")] public void CS0191ERR_AssgReadonly() { var source = @"class MyClass { public readonly int TestInt = 6; // OK to assign to readonly field in declaration public MyClass() { TestInt = 11; // OK to assign to readonly field in constructor TestInt = 12; // OK to assign to readonly field multiple times in constructor this.TestInt = 13; // OK to assign with explicit this receiver MyClass t = this; t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this } public void TestReadOnly() { TestInt = 19; // CS0191 } public static void Main() { } } class MyDerived : MyClass { MyDerived() { TestInt = 15; // CS0191 - not in declaring class } } "; CreateCompilation(source).VerifyDiagnostics( // (28,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 15; // CS0191 - not in declaring class Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(28, 9), // (11,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this Diagnostic(ErrorCode.ERR_AssgReadonly, "t.TestInt").WithLocation(11, 9), // (16,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 19; // CS0191 Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(16, 9)); } [WorkItem(538009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538009")] [Fact] public void CS0192ERR_RefReadonly() { var text = @" class MyClass { public readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // OK } public void PassReadOnlyRef() { TestMethod(ref TestInt); // CS0192 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonly, Line = 17, Column = 24 } }); } [Fact] public void CS0193ERR_PtrExpected() { var text = @" using System; public struct Age { public int AgeYears; public int AgeMonths; public int AgeDays; } public class MyClass { public static void SetAge(ref Age anAge, int years, int months, int days) { anAge->Months = 3; // CS0193, anAge is not a pointer // try the following line instead // anAge.AgeMonths = 3; } public static void Main() { Age MyAge = new Age(); Console.WriteLine(MyAge.AgeMonths); SetAge(ref MyAge, 22, 4, 15); Console.WriteLine(MyAge.AgeMonths); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PtrExpected, Line = 15, Column = 7 } }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CS0196ERR_PtrIndexSingle() { var text = @" unsafe public class MyClass { public static void Main () { int *i = null; int j = 0; j = i[1,2]; // CS0196 // try the following line instead // j = i[1]; } }"; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,11): error CS0196: A pointer must be indexed by only one value // j = i[1,2]; // CS0196 Diagnostic(ErrorCode.ERR_PtrIndexSingle, "i[1,2]")); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[1,2]", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1,2]') Children(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32*, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1,2]') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); } [Fact] public void CS0198ERR_AssgReadonlyStatic() { var text = @" public class MyClass { public static readonly int TestInt = 6; static MyClass() { TestInt = 7; TestInt = 8; MyClass.TestInt = 7; } public MyClass() { TestInt = 11; // CS0198, constructor is not static and readonly field is } private void InstanceMethod() { TestInt = 12; // CS0198 } private void StaticMethod() { TestInt = 13; // CS0198 } public static void Main() { } } class MyDerived : MyClass { static MyDerived() { MyClass.TestInt = 14; // CS0198, not in declaring class } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 15, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 20, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 25, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 37, Column = 9 }, }); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() { var text = @"public static class Goo<T> { static Goo() { Goo<int>.X = 1; Goo<int>.Y = 2; Goo<T>.Y = 3; } public static readonly int X; public static int Y { get; } }"; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (5,9): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) // Goo<int>.X = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, "Goo<int>.X").WithLocation(5, 9), // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation02() { var text = @"using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine(Goo<long>.x); Console.WriteLine(Goo<int>.x); Console.WriteLine(Goo<string>.x); Console.WriteLine(Goo<int>.x); } } public static class Goo<T> { static Goo() { Console.WriteLine(""initializing for "" + typeof(T)); Goo<int>.x = typeof(T).Name; } public static readonly string x; }"; var expectedOutput = @"initializing for System.Int64 initializing for System.Int32 Int64 initializing for System.String String "; // Although we accept this nasty code, it will not verify. CompileAndVerify(text, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void CS0199ERR_RefReadonlyStatic() { var text = @" class MyClass { public static readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // CS0199, TestInt is static } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonlyStatic, Line = 13, Column = 24 } }); } [Fact] public void CS0200ERR_AssgReadonlyProp01() { var source = @"abstract class A { internal static A P { get { return null; } } internal object Q { get; set; } public abstract object R { get; } } class B : A { public override object R { get { return null; } } } class Program { static void M(B b) { B.P.Q = null; B.P = null; // CS0200 b.R = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0200: Property or indexer 'A.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "B.P").WithArguments("A.P").WithLocation(16, 9), // (17,9): error CS0200: Property or indexer 'B.R' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.R").WithArguments("B.R").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp02() { var source = @"class A { public virtual A P { get; set; } public A Q { get { return null; } } } class B : A { public override A P { get { return null; } } } class Program { static void M(B b) { b.P = null; b.Q = null; // CS0200 b.Q.P = null; b.P.Q = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (15,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.Q").WithArguments("A.Q").WithLocation(15, 9), // (17,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P.Q").WithArguments("A.Q").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp03() { var source = @"class C { static int P { get { return 0; } } int Q { get { return 0; } } static void M(C c) { ++P; ++c.Q; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,11): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(7, 11), // (8,11): error CS0200: Property or indexer 'C.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Q").WithArguments("C.Q").WithLocation(8, 11)); } [Fact] public void CS0200ERR_AssgReadonlyProp04() { var source = @"class C { object P { get { P = null; return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,22): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(3, 22)); } [Fact] public void CS0200ERR_AssgReadonlyProp05() { CreateCompilation( @"class C { int this[int x] { get { return x; } } void M(int b) { this[0] = b; this[1]++; this[2] += 1; } }") .VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[0]").WithArguments("C.this[int]"), // (7,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[1]").WithArguments("C.this[int]"), // (8,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[2]").WithArguments("C.this[int]")); } [Fact] public void CS0200ERR_AssgReadonlyProp06() { var source1 = @"public class A { public virtual object P { get { return null; } private set { } } } public class B : A { public override object P { get { return null; } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'B.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P").WithArguments("B.P").WithLocation(6, 9)); } [Fact] public void CS0201ERR_IllegalStatement1() { var text = @" public class MyList<T> { public void Add(T x) { int i = 0; if ( (object)x == null) { checked(i++); // CS0201 // OK checked { i++; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (9,10): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Diagnostic(ErrorCode.ERR_IllegalStatement, "checked(i++)")); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2() { var text = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; CreateCompilation(text, parseOptions: TestOptions.Regular.WithTuplesFeature()).VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2WithCSharp6() { var test = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; var comp = CreateCompilation(new[] { Parse(test, options: TestOptions.Regular6) }, new MetadataReference[] { }); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact] public void CS0202ERR_BadGetEnumerator() { var text = @" public class C1 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public static implicit operator C1 (int c1) { return 0; } } public class C2 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public C1[] GetEnumerator () { return null; } } public class MainClass { public static void Main () { C2 c2 = new C2(); foreach (C1 x in c2) // CS0202 { System.Console.WriteLine(x.Current); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadGetEnumerator, Line = 50, Column = 24 } }); } // [Fact()] // public void CS0204ERR_TooManyLocals() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_TooManyLocals, Line = 8, Column = 13 } } // ); // } [Fact()] public void CS0205ERR_AbstractBaseCall() { var text = @"abstract class A { abstract public void M(); abstract protected object P { get; } } class B : A { public override void M() { base.M(); // CS0205 object o = base.P; // CS0205 } protected override object P { get { return null; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 10, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 11, Column = 20 }); } [Fact] public void CS0205ERR_AbstractBaseCall_Override() { var text = @" public class Base1 { public virtual long Property1 { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } void test1() { Property1 += 1; } } public class Derived : Base2 { public override long Property1 { get { return 1; } set { } } void test2() { base.Property1++; base.Property1 = 2; long x = base.Property1; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1"), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1")); } [Fact] public void CS0206ERR_RefProperty() { var text = @"class C { static int P { get; set; } object Q { get; set; } static void M(ref int i) { } static void M(out object o) { o = null; } void M() { M(ref P); // CS0206 M(out this.Q); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "P").WithArguments("C.P"), // (15,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this.Q").WithArguments("C.Q")); } [Fact] public void CS0206ERR_RefProperty_Indexers() { var text = @"class C { int this[int x] { get { return x; } set { } } static void R(ref int i) { } static void O(out int o) { o = 0; } void M() { R(ref this[0]); // CS0206 O(out this[0]); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]"), // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]")); } [Fact] public void CS0208ERR_ManagedAddr01() { var text = @" class myClass { public int a = 98; } struct myProblemStruct { string s; float f; } struct myGoodStruct { int i; float f; } public class MyClass { unsafe public static void Main() { // myClass is a class, a managed type. myClass s = new myClass(); myClass* s2 = &s; // CS0208 // The struct contains a string, a managed type. int i = sizeof(myProblemStruct); //CS0208 // The struct contains only value types. i = sizeof(myGoodStruct); //OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (25,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "myClass*").WithArguments("myClass"), // (25,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("myClass"), // (28,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myProblemStruct') // int i = sizeof(myProblemStruct); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(myProblemStruct)").WithArguments("myProblemStruct"), // (9,12): warning CS0169: The field 'myProblemStruct.s' is never used // string s; Diagnostic(ErrorCode.WRN_UnreferencedField, "s").WithArguments("myProblemStruct.s"), // (10,11): warning CS0169: The field 'myProblemStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myProblemStruct.f"), // (15,9): warning CS0169: The field 'myGoodStruct.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("myGoodStruct.i"), // (16,11): warning CS0169: The field 'myGoodStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myGoodStruct.f")); } [Fact] public void CS0208ERR_ManagedAddr02() { var source = @"enum E { } delegate void D(); struct S { } interface I { } unsafe class C { object* _object; void* _void; bool* _bool; char* _char; sbyte* _sbyte; byte* _byte; short* _short; ushort* _ushort; int* _int; uint* _uint; long* _long; ulong* _ulong; decimal* _decimal; float* _float; double* _double; string* _string; System.IntPtr* _intptr; System.UIntPtr* _uintptr; int** _intptr2; int?* _nullable; dynamic* _dynamic; E* e; D* d; S* s; I* i; C* c; }"; CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll) .GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error) .Verify( // (22,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // string* _string; Diagnostic(ErrorCode.ERR_ManagedAddr, "_string").WithArguments("string").WithLocation(22, 13), // (27,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // dynamic* _dynamic; Diagnostic(ErrorCode.ERR_ManagedAddr, "_dynamic").WithArguments("dynamic").WithLocation(27, 14), // (29,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('D') // D* d; Diagnostic(ErrorCode.ERR_ManagedAddr, "d").WithArguments("D").WithLocation(29, 8), // (31,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('I') // I* i; Diagnostic(ErrorCode.ERR_ManagedAddr, "i").WithArguments("I").WithLocation(31, 8), // (32,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // C* c; Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("C").WithLocation(32, 8), // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // object* _object; Diagnostic(ErrorCode.ERR_ManagedAddr, "_object").WithArguments("object").WithLocation(7, 13)); } [Fact] public void CS0209ERR_BadFixedInitType() { var text = @" class Point { public int x, y; } public class MyClass { unsafe public static void Main() { Point pt = new Point(); fixed (int i) // CS0209 { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,18): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_BadFixedInitType, "i"), // (13,18): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_FixedMustInit, "i"), // (4,15): warning CS0649: Field 'Point.x' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Point.x", "0"), // (4,18): warning CS0649: Field 'Point.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("Point.y", "0")); } [Fact] public void CS0210ERR_FixedMustInit() { var text = @" using System.IO; class Test { static void Main() { using (StreamWriter w) // CS0210 { w.WriteLine(""Hello there""); } using (StreamWriter x, y) // CS0210, CS0210 { } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter w) // CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "w").WithLocation(7, 27), // (12,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(12, 27), // (12,30): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "y").WithLocation(12, 30), // (9,10): error CS0165: Use of unassigned local variable 'w' // w.WriteLine("Hello there"); Diagnostic(ErrorCode.ERR_UseDefViolation, "w").WithArguments("w").WithLocation(9, 10) ); } [Fact] public void CS0211ERR_InvalidAddrOp() { var text = @" public class MyClass { unsafe public void M() { int a = 0, b = 0; int *i = &(a + b); // CS0211, the addition of two local variables // try the following line instead // int *i = &a; } public static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0211: Cannot take the address of the given expression // int *i = &(a + b); // CS0211, the addition of two local variables Diagnostic(ErrorCode.ERR_InvalidAddrOp, "a + b")); } [Fact] public void CS0212ERR_FixedNeeded() { var text = @" public class A { public int iField = 5; unsafe public void M() { A a = new A(); int* ptr = &a.iField; // CS0212 } // OK unsafe public void M2() { A a = new A(); fixed (int* ptr = &a.iField) {} } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* ptr = &a.iField; // CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&a.iField")); } [Fact] public void CS0213ERR_FixedNotNeeded() { var text = @" public class MyClass { unsafe public static void Main() { int i = 45; fixed (int *j = &i) { } // CS0213 // try the following line instead // int* j = &i; int[] a = new int[] {1,2,3}; fixed (int *b = a) { fixed (int *c = b) { } // CS0213 // try the following line instead // int *c = b; } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,23): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int *j = &i) { } // CS0213 Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&i").WithLocation(7, 23), // (14,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int *c = b) { } // CS0213 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "b").WithLocation(14, 26)); } [Fact] public void CS0217ERR_BadBoolOp() { // Note that the wording of this error message has changed. var text = @" public class MyClass { public static bool operator true (MyClass f) { return false; } public static bool operator false (MyClass f) { return false; } public static int operator & (MyClass f1, MyClass f2) { return 0; } public static void Main() { MyClass f = new MyClass(); int i = f && f; // CS0217 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,15): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('MyClass.operator &(MyClass, MyClass)') must have the same return type and parameter types // int i = f && f; // CS0217 Diagnostic(ErrorCode.ERR_BadBoolOp, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)")); } // CS0220 ERR_CheckedOverflow - see ConstantTests [Fact] public void CS0221ERR_ConstOutOfRangeChecked01() { string text = @"class MyClass { static void F(int x) { } static void M() { F((int)0xFFFFFFFF); // CS0221 F(unchecked((int)uint.MaxValue)); F(checked((int)(uint.MaxValue - 1))); // CS0221 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0221: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)0xFFFFFFFF").WithArguments("4294967295", "int"), // (8,19): error CS0221: Constant value '4294967294' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)(uint.MaxValue - 1)").WithArguments("4294967294", "int")); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked02() { string text = @"enum E : byte { A, B = 0xfe, C } class C { const int F = (int)(E.C + 1); // CS0221 const int G = (int)unchecked(1 + E.C); const int H = (int)checked(E.A - 1); // CS0221 } "; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0031: Constant value '256' cannot be converted to a 'E' Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.C + 1").WithArguments("256", "E"), // (6,32): error CS0221: Constant value '-1' cannot be converted to a 'E' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.A - 1").WithArguments("-1", "E")); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact(Skip = "1119609")] public void CS0221ERR_ConstOutOfRangeChecked03() { var text = @"public class MyClass { decimal x1 = (decimal)double.PositiveInfinity; //CS0221 decimal x2 = (decimal)double.NegativeInfinity; //CS0221 decimal x3 = (decimal)double.NaN; //CS0221 decimal x4 = (decimal)double.MaxValue; //CS0221 public static void Main() {} } "; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (4,18): error CS0031: Constant value '-Infinity' cannot be converted to a 'decimal' // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NegativeInfinity").WithArguments("-Infinity", "decimal"), // (5,18): error CS0031: Constant value 'NaN' cannot be converted to a 'decimal' // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NaN").WithArguments("NaN", "decimal"), // (6,18): error CS0031: Constant value '1.79769313486232E+308' cannot be converted to a 'decimal' // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.MaxValue").WithArguments("1.79769313486232E+308", "decimal"), // (3,13): warning CS0414: The field 'MyClass.x1' is assigned but its value is never used // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x1").WithArguments("MyClass.x1"), // (4,13): warning CS0414: The field 'MyClass.x2' is assigned but its value is never used // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x2").WithArguments("MyClass.x2"), // (5,13): warning CS0414: The field 'MyClass.x3' is assigned but its value is never used // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x3").WithArguments("MyClass.x3"), // (6,13): warning CS0414: The field 'MyClass.x4' is assigned but its value is never used // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x4").WithArguments("MyClass.x4")); } [Fact] public void CS0226ERR_IllegalArglist() { var text = @" public class C { public static int Main () { __arglist(1,""This is a string""); // CS0226 return 0; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_IllegalArglist, @"__arglist(1,""This is a string"")")); } // [Fact()] // public void CS0228ERR_NoAccessibleMember() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoAccessibleMember, Line = 31, Column = 17 } } // ); // } [Fact] public void CS0229ERR_AmbigMember() { var text = @" interface IList { int Count { get; set; } void Counter(); } interface Icounter { double Count { get; set; } } interface IListCounter : IList , Icounter {} class MyClass { void Test(IListCounter x) { x.Count = 1; // CS0229 // Try one of the following lines instead: // ((IList)x).Count = 1; // or // ((Icounter)x).Count = 1; } public static void Main() {} } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigMember, Line = 28, Column = 11 } }); } [Fact] public void CS0233ERR_SizeofUnsafe() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct S { public int a; } public class MyClass { public static void Main() { S myS = new S(); Console.WriteLine(sizeof(S)); // CS0233 // Try the following line instead: // Console.WriteLine(Marshal.SizeOf(myS)); } } "; CreateCompilation(text).VerifyDiagnostics( // (16,27): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // Console.WriteLine(sizeof(S)); // CS0233 Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S"), // (15,11): warning CS0219: The variable 'myS' is assigned but its value is never used // S myS = new S(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "myS").WithArguments("myS")); } [Fact] public void CS0236ERR_FieldInitRefNonstatic() { var text = @" public class MyClass { int[] instanceArray; static int[] staticArray; static int staticField = 1; const int constField = 1; int a; int b = 1; int c = b; //CS0236 int d = this.b; //CS0027 int e = InstanceMethod(); //CS0236 int f = this.InstanceMethod(); //CS0027 int g = StaticMethod(); int h = MyClass.StaticMethod(); int i = GenericInstanceMethod<int>(1); //CS0236 int j = this.GenericInstanceMethod<int>(1); //CS0027 int k = GenericStaticMethod<int>(1); int l = MyClass.GenericStaticMethod<int>(1); int m = InstanceProperty; //CS0236 int n = this.InstanceProperty; //CS0027 int o = StaticProperty; int p = MyClass.StaticProperty; int q = instanceArray[0]; //CS0236 int r = this.instanceArray[0]; //CS0027 int s = staticArray[0]; int t = MyClass.staticArray[0]; int u = staticField; int v = MyClass.staticField; int w = constField; int x = MyClass.constField; MyClass() { a = b; } int InstanceMethod() { return a; } static int StaticMethod() { return 1; } T GenericInstanceMethod<T>(T t) { return t; } static T GenericStaticMethod<T>(T t) { return t; } int InstanceProperty { get { return a; } } static int StaticProperty { get { return 1; } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.b' // int c = b; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "b").WithArguments("MyClass.b").WithLocation(12, 13), // (13,13): error CS0027: Keyword 'this' is not available in the current context // int d = this.b; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 13), // (14,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceMethod()' // int e = InstanceMethod(); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceMethod").WithArguments("MyClass.InstanceMethod()").WithLocation(14, 13), // (15,13): error CS0027: Keyword 'this' is not available in the current context // int f = this.InstanceMethod(); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(15, 13), // (18,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.GenericInstanceMethod<int>(int)' // int i = GenericInstanceMethod<int>(1); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "GenericInstanceMethod<int>").WithArguments("MyClass.GenericInstanceMethod<int>(int)").WithLocation(18, 13), // (19,13): error CS0027: Keyword 'this' is not available in the current context // int j = this.GenericInstanceMethod<int>(1); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(19, 13), // (22,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceProperty' // int m = InstanceProperty; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceProperty").WithArguments("MyClass.InstanceProperty").WithLocation(22, 13), // (23,13): error CS0027: Keyword 'this' is not available in the current context // int n = this.InstanceProperty; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(23, 13), // (26,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.instanceArray' // int q = instanceArray[0]; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "instanceArray").WithArguments("MyClass.instanceArray").WithLocation(26, 13), // (27,13): error CS0027: Keyword 'this' is not available in the current context // int r = this.instanceArray[0]; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 13), // (4,11): warning CS0649: Field 'MyClass.instanceArray' is never assigned to, and will always have its default value null // int[] instanceArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceArray").WithArguments("MyClass.instanceArray", "null").WithLocation(4, 11), // (5,18): warning CS0649: Field 'MyClass.staticArray' is never assigned to, and will always have its default value null // static int[] staticArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticArray").WithArguments("MyClass.staticArray", "null").WithLocation(5, 18), // (33,9): warning CS0414: The field 'MyClass.x' is assigned but its value is never used // int x = MyClass.constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("MyClass.x").WithLocation(33, 9), // (32,9): warning CS0414: The field 'MyClass.w' is assigned but its value is never used // int w = constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "w").WithArguments("MyClass.w").WithLocation(32, 9) ); } [Fact] public void CS0236ERR_FieldInitRefNonstaticMethodGroups() { var text = @" delegate void F(); public class MyClass { F a = Static; F b = MyClass.Static; F c = Static<int>; F d = MyClass.Static<int>; F e = Instance; F f = this.Instance; F g = Instance<int>; F h = this.Instance<int>; static void Static() { } static void Static<T>() { } void Instance() { } void Instance<T>() { } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib( text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 9, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 10, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 11, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 12, Column = 11 }, }); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstaticProperty() { CreateCompilation( @" enum ProtectionLevel { Privacy = 0 } class F { const ProtectionLevel p = ProtectionLevel.Privacy; // CS0236 int ProtectionLevel { get { return 0; } } } ") .VerifyDiagnostics( // (9,29): error CS0236: A field initializer cannot reference the non-static field, method, or property 'F.ProtectionLevel' // const ProtectionLevel p = ProtectionLevel.Privacy; // CS0120 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "ProtectionLevel").WithArguments("F.ProtectionLevel")); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstatic_ObjectInitializer() { CreateCompilation( @" public class Goo { public int i; public string s; } public class MemberInitializerTest { private int i =10; private string s = ""abc""; private Goo f = new Goo{i = i, s = s}; public static void Main() { } } ") .VerifyDiagnostics( // (12,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.i' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "i").WithArguments("MemberInitializerTest.i").WithLocation(12, 33), // (12,40): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.s' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "s").WithArguments("MemberInitializerTest.s").WithLocation(12, 40)); } [Fact] public void CS0236ERR_FieldInitRefNonstatic_AnotherInitializer() { CreateCompilation( @" class TestClass { int P1 { get; } int y = (P1 = 123); int y1 { get; } = (P1 = 123); static void Main() { } } ") .VerifyDiagnostics( // (6,14): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(6, 14), // (7,24): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y1 { get; } = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(7, 24) ); } [Fact] public void CS0242ERR_VoidError() { var text = @" class TestClass { public unsafe void Test() { void* p = null; p++; //CS0242 p += 2; //CS0242 void* q = p + 1; //CS0242 long diff = q - p; //CS0242 var v = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,9): error CS0242: The operation in question is undefined on void pointers // p++; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p++"), // (8,9): error CS0242: The operation in question is undefined on void pointers // p += 2; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p += 2"), // (9,19): error CS0242: The operation in question is undefined on void pointers // void* q = p + 1; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p + 1"), // (10,21): error CS0242: The operation in question is undefined on void pointers // long diff = q - p; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "q - p"), // (11,17): error CS0242: The operation in question is undefined on void pointers // var v = *p; Diagnostic(ErrorCode.ERR_VoidError, "*p")); } [Fact] public void CS0244ERR_PointerInAsOrIs() { var text = @" class UnsafeTest { unsafe static void SquarePtrParam (int* p) { bool b = p is object; // CS0244 p is pointer } unsafe public static void Main() { int i = 5; SquarePtrParam (&i); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,16): error CS0244: Neither 'is' nor 'as' is valid on pointer types // bool b = p is object; // CS0244 p is pointer Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "p is object")); } [Fact] public void CS0245ERR_CallingFinalizeDeprecated() { var text = @" class MyClass // : IDisposable { /* public void Dispose() { // cleanup code goes here } */ void m() { this.Finalize(); // CS0245 // this.Dispose(); } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,7): error CS0245: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. Diagnostic(ErrorCode.ERR_CallingFinalizeDeprecated, "this.Finalize()")); } [WorkItem(540722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540722")] [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { CreateCompilation(@" namespace nms { public class Mine { private static int retval = 5; public static int Main() { try { } catch (e) { } return retval; } }; } ") .VerifyDiagnostics( // (10,20): error CS0246: The type or namespace name 'e' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "e").WithArguments("e")); } [WorkItem(528446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528446")] [Fact] public void CS0246ERR_SingleTypeNameNotFoundNoCS8000() { CreateCompilation(@" class Test { void Main() { var sum = new j(); } } ") .VerifyDiagnostics( // (11,20): error CS0246: The type or namespace name 'j' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "j").WithArguments("j")); } [Fact] public void CS0247ERR_NegativeStackAllocSize() { var text = @" public class MyClass { unsafe public static void Main() { int *p = stackalloc int [-30]; // CS0247 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,32): error CS0247: Cannot use a negative size with stackalloc // int *p = stackalloc int [-30]; // CS0247 Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-30")); } [Fact] public void CS0248ERR_NegativeArraySize() { var text = @" class MyClass { public static void Main() { int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes int[] myArray3 = new int[3000000000u]; // slightly different code path for uint array sizes var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; var myArray5 = new object[-1L] {null}; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,33): error CS0248: Cannot create an array with a negative size // int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number Diagnostic(ErrorCode.ERR_NegativeArraySize, "-3").WithLocation(6, 33), // (7,34): error CS0248: Cannot create an array with a negative size // int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes Diagnostic(ErrorCode.ERR_NegativeArraySize, "-5000000000").WithLocation(7, 34), // (9,35): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-2").WithLocation(9, 35), // (9,42): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1").WithLocation(9, 42), // (10,35): error CS0248: Cannot create an array with a negative size // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1L").WithLocation(10, 35), // (10,35): error CS0150: A constant value is expected // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_ConstantExpected, "-1L").WithLocation(10, 35)); } [WorkItem(528912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528912")] [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" class B { } class C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()")); } [Fact] public void CS0254ERR_BadCastInFixed() { var text = @" class Point { public uint x, y; } class FixedTest { unsafe static void SquarePtrParam (int* p) { *p *= *p; } unsafe public static void Main() { Point pt = new Point(); pt.x = 5; pt.y = 6; fixed (int* p = (int*)&pt.x) // CS0254 // try the following line instead // fixed (uint* p = &pt.x) { SquarePtrParam ((int*)p); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (20,23): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = (int*)&pt.x) // CS0254 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)&pt.x").WithLocation(20, 23)); } [Fact] public void CS0255ERR_StackallocInFinally() { var text = @" unsafe class Test { void M() { try { // Something } finally { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0255ERR_StackallocInCatch() { var text = @" unsafe class Test { void M() { try { // Something } catch { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0266ERR_NoImplicitConvCast01() { var text = @" class MyClass { public static void Main() { object obj = ""MyString""; // Cannot implicitly convert 'object' to 'MyClass' MyClass myClass = obj; // CS0266 // Try this line instead // MyClass c = ( MyClass )obj; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConvCast, Line = 8, Column = 27 } }); } [Fact] public void CS0266ERR_NoImplicitConvCast02() { var source = @"class C { const int f = 0L; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // const int f = 0L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0L").WithArguments("long", "int").WithLocation(3, 19)); } [Fact] public void CS0266ERR_NoImplicitConvCast03() { var source = @"class C { static void M() { const short s = 1L; } } "; CreateCompilation(source).VerifyDiagnostics( // (5,25): error CS0266: Cannot implicitly convert type 'long' to 'short'. An explicit conversion exists (are you missing a cast?) // const short s = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "short").WithLocation(5, 25), // (5,21): warning CS0219: The variable 's' is assigned but its value is never used // const short s = 1L; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(5, 21)); } [Fact] public void CS0266ERR_NoImplicitConvCast04() { var source = @"enum E { A = 1 } class C { E f = 2; // CS0266 E g = E.A; void M() { f = E.A; g = 'c'; // CS0266 } } "; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0266: Cannot implicitly convert type 'int' to 'E'. An explicit conversion exists (are you missing a cast?) // E f = 2; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "2").WithArguments("int", "E").WithLocation(4, 11), // (9,13): error CS0266: Cannot implicitly convert type 'char' to 'E'. An explicit conversion exists (are you missing a cast?) // g = 'c'; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'c'").WithArguments("char", "E").WithLocation(9, 13), // (4,7): warning CS0414: The field 'C.f' is assigned but its value is never used // E f = 2; // CS0266 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f").WithLocation(4, 7), // (5,7): warning CS0414: The field 'C.g' is assigned but its value is never used // E g = E.A; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g").WithLocation(5, 7)); } [Fact] public void CS0266ERR_NoImplicitConvCast05() { var source = @"enum E : byte { A = 'a', // CS0266 B = 0xff, } "; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0266: Cannot implicitly convert type 'char' to 'byte'. An explicit conversion exists (are you missing a cast?) // A = 'a', // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'a'").WithArguments("char", "byte").WithLocation(3, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast06() { var source = @"enum E { A = 1, B = 1L // CS0266 } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // B = 1L // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(4, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast07() { // No errors var source = "enum E { A, B = A }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast08() { // No errors var source = @"enum E { A = 1, B } enum F { X = E.A + 1, Y } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast09() { var source = @"enum E { A = F.A, B = F.B, C = G.A, D = G.B, } enum F : short { A = 1, B } enum G : long { A = 1, B } "; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // C = G.A, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.A").WithArguments("long", "int").WithLocation(5, 9), // (6,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // D = G.B, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.B").WithArguments("long", "int").WithLocation(6, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast10() { var source = @"class C { public const int F = D.G + 1; } class D { public const int G = E.H + 1; } class E { public const int H = 1L; } "; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // public const int H = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(11, 26)); } [Fact()] public void CS0266ERR_NoImplicitConvCast11() { string text = @"class Program { static void Main(string[] args) { bool? b = true; int result = b ? 0 : 1; // Compiler error } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("bool?", "bool")); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast12() { string text = @" class C1 { public static void Main() { var cube = new int[Number.One][]; } } enum Number { One, Two } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0266: Cannot implicitly convert type 'Number' to 'int'. An explicit conversion exists (are you missing a cast?) // var cube = new int[Number.One][]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Number.One").WithArguments("Number", "int").WithLocation(6, 28)); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast13() { string text = @" class C1 { public static void Main() { double x = 5; int[] arr4 = new int[x];// Invalid float y = 5; int[] arr5 = new int[y];// Invalid decimal z = 5; int[] arr6 = new int[z];// Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (7,30): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr4 = new int[x];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("double", "int").WithLocation(7, 30), // (10,30): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr5 = new int[y];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("float", "int").WithLocation(10, 30), // (13,30): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr6 = new int[z];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "z").WithArguments("decimal", "int").WithLocation(13, 30)); } [Fact] public void CS0266ERR_NoImplicitConvCast14() { string source = @" class C { public unsafe void M(int* p, object o) { _ = p[o]; // error with span on 'o' _ = p[0]; // ok } } "; CreateCompilation(source, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // _ = p[o]; // error with span on 'o' Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 15)); } [Fact] public void CS0266ERR_NoImplicitConvCast15() { string source = @" class C { public void M(object o) { int[o] x; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[o]; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[o]").WithLocation(6, 12), // (6,13): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // int[o]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 13), // (6,16): warning CS0168: The variable 'x' is declared but never used // int[o] x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 16)); } [Fact] public void CS0269ERR_UseDefViolationOut() { var text = @" class C { public static void F(out int i) { try { // Assignment occurs, but compiler can't verify it i = 1; } catch { } int k = i; // CS0269 i = 1; } public static void Main() { int myInt; F(out myInt); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationOut, Line = 15, Column = 17 } }); } [Fact] public void CS0271ERR_InaccessibleGetter01() { var source = @"class C { internal static object P { private get; set; } public C Q { protected get { return null; } set { } } } class P { static void M(C c) { object o = C.P; M(c.Q); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,20): error CS0271: The property or indexer 'C.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "C.P").WithArguments("C.P").WithLocation(10, 20), // (11,11): error CS0271: The property or indexer 'C.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "c.Q").WithArguments("C.Q").WithLocation(11, 11)); } [Fact] public void CS0271ERR_InaccessibleGetter02() { var source = @"class A { public virtual object P { protected get; set; } } class B : A { public override object P { set { } } void M() { object o = P; // no error } } class C { void M(B b) { object o = b.P; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,20): error CS0271: The property or indexer 'B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("B.P").WithLocation(17, 20)); } [Fact] public void CS0271ERR_InaccessibleGetter03() { var source = @"namespace N1 { class A { void M(N2.B b) { object o = b.P; } } } namespace N2 { class B : N1.A { public object P { protected get; set; } } }"; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0271: The property or indexer 'N2.B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("N2.B.P").WithLocation(7, 24)); } [Fact] public void CS0271ERR_InaccessibleGetter04() { var source = @"class A { static public object P { protected get; set; } static internal object Q { private get; set; } static void M() { object o = B.Q; // no error o = A.Q; // no error } } class B : A { static void M() { object o = B.P; // no error o = P; // no error o = Q; // CS0271 } } class C { static void M() { object o = B.P; // CS0271 o = A.Q; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "Q").WithArguments("A.Q").WithLocation(17, 13), // (24,20): error CS0271: The property or indexer 'A.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "B.P").WithArguments("A.P").WithLocation(24, 20), // (25,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "A.Q").WithArguments("A.Q").WithLocation(25, 13)); } [Fact] public void CS0271ERR_InaccessibleGetter05() { CreateCompilation( @"class A { public object this[int x] { protected get { return null; } set { } } internal object this[string s] { private get { return null; } set { } } void M() { object o = new B()[""hello""]; // no error o = new A()[""hello""]; // no error } } class B : A { void M() { object o = new B()[0]; // no error o = this[0]; // no error o = this[""hello""]; // CS0271 } } class C { void M() { object o = new B()[0]; // CS0271 o = new A()[""hello""]; // CS0271 } }") .VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"this[""hello""]").WithArguments("A.this[string]"), // (24,20): error CS0271: The property or indexer 'A.this[int]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "new B()[0]").WithArguments("A.this[int]"), // (25,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"new A()[""hello""]").WithArguments("A.this[string]")); } [Fact] public void CS0272ERR_InaccessibleSetter01() { var source = @"namespace N { class C { internal object P { get; private set; } static public C Q { get { return null; } protected set { } } } class P { static void M(C c) { c.P = c; C.Q = c; } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,13): error CS0272: The property or indexer 'N.C.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "c.P").WithArguments("N.C.P").WithLocation(12, 13), // (13,13): error CS0272: The property or indexer 'N.C.Q' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "C.Q").WithArguments("N.C.Q").WithLocation(13, 13)); } [Fact] public void CS0272ERR_InaccessibleSetter02() { var source = @"namespace N1 { abstract class A { public virtual object P { get; protected set; } } } namespace N2 { class B : N1.A { public override object P { get { return null; } } void M() { P = null; // no error } } } class C { void M(N2.B b) { b.P = null; // CS0272 } }"; CreateCompilation(source).VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b.P").WithArguments("N2.B.P").WithLocation(23, 9)); } [Fact] public void CS0272ERR_InaccessibleSetter03() { CreateCompilation( @"namespace N1 { abstract class A { public virtual object this[int x] { get { return null; } protected set { } } } } namespace N2 { class B : N1.A { public override object this[int x] { get { return null; } } void M() { this[0] = null; // no error } } } class C { void M(N2.B b) { b[0] = null; // CS0272 } } ") .VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.this[int]' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b[0]").WithArguments("N2.B.this[int]")); } [Fact] public void CS0283ERR_BadConstType() { // Test for both ERR_BadConstType and an error for RHS to ensure // the RHS is not reported multiple times (when calculating the // constant value for the symbol and also when binding). var source = @"struct S { static void M(object o) { const S s = 2; M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0283: The type 'S' cannot be declared const // const S s = 2; Diagnostic(ErrorCode.ERR_BadConstType, "S").WithArguments("S").WithLocation(5, 15), // (5,21): error CS0029: Cannot implicitly convert type 'int' to 'S' // const S s = 2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "S").WithLocation(5, 21)); } [Fact] public void CS0304ERR_NoNewTyvar01() { var source = @"struct S<T, U> where U : new() { void M<V>() { object o; o = new T(); o = new U(); o = new V(); } } class C<T, U> where T : struct where U : class { void M<V, W>() where V : struct where W : class, new() { object o; o = new T(); o = new U(); o = new V(); o = new W(); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T()").WithArguments("T").WithLocation(6, 13), // (8, 13): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new V()").WithArguments("V").WithLocation(8, 13), // (21,13): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(21, 13)); } [WorkItem(542377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542377")] [Fact] public void CS0304ERR_NoNewTyvar02() { var source = @"struct S { } class C { } abstract class A<T> { public abstract U F<U>() where U : T; } class B1 : A<int> { public override U F<U>() { return new U(); } } class B2 : A<S> { public override U F<U>() { return new U(); } } class B3 : A<C> { public override U F<U>() { return new U(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,39): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(17, 39)); } [WorkItem(542547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542547")] [Fact] public void CS0305ERR_BadArity() { var text = @" public class NormalType { public static int M1<T1>(T1 p1, T1 p2) { return 0; } public static int Main() { M1<int, >(10, 11); return -1; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,17): error CS1031: Type expected Diagnostic(ErrorCode.ERR_TypeExpected, ">"), // (7,9): error CS0305: Using the generic method 'NormalType.M1<T1>(T1, T1)' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<int, >").WithArguments("NormalType.M1<T1>(T1, T1)", "method", "1")); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied01() { var text = @"class A<T> { } class B { private B() { } } delegate void D(); enum E { } struct S { } class C<T, U> where T : new() { static void M<V>() where V : new() { M<A<int>>(); M<B>(); M<D>(); M<E>(); M<object>(); M<int>(); M<S>(); M<T>(); M<U>(); M<B, B>(); M<T, U>(); M<T, V>(); M<T[]>(); M<dynamic>(); } static void M<V, W>() where V : new() where W : new() { } }"; CreateCompilation(text).VerifyDiagnostics( // (14,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<T, U>.M<V>()", "V", "B").WithLocation(14, 9), // (15,9): error CS0310: 'D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<D>").WithArguments("C<T, U>.M<V>()", "V", "D").WithLocation(15, 9), // (21,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<U>").WithArguments("C<T, U>.M<V>()", "V", "U").WithLocation(21, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "V", "B").WithLocation(22, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "W", "B").WithLocation(22, 9), // (23,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T, U>").WithArguments("C<T, U>.M<V, W>()", "W", "U").WithLocation(23, 9), // (25,9): error CS0310: 'T[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T[]>").WithArguments("C<T, U>.M<V>()", "V", "T[]").WithLocation(25, 9)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied02() { var text = @"class A { } class B { internal B() { } } class C<T> where T : new() { internal static void M<U>() where U : new() { } internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> } delegate T D<T>() where T : new(); static class E { internal static void M<T>(this object o) where T : new() { } internal static void F<T>(D<T> d) where T : new() { } } class F<T, U> where U : new() { } abstract class G { } class H : G { } interface I { } struct S { private S(object o) { } static void M() { C<A>.M<A>(); C<A>.M<B>(); C<B>.M<A>(); C<B>.M<B>(); C<G>.M<H>(); C<H>.M<G>(); C<I>.M<S>(); E.F(S.F<A>); E.F(S.F<B>); E.F(S.F<C<A>>); E.F(S.F<C<B>>); var o = new object(); o.M<A>(); o.M<B>(); o = new F<A, B>(); o = new F<B, A>(); } static T F<T>() { return default(T); } }"; // Note that none of these errors except the first one are reported by the native compiler, because // it does not report additional errors after an error is found in a formal parameter of a method. CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (9,36): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' // internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "d").WithArguments("D<T>", "T", "U").WithLocation(9, 36), // (29,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<A>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<A>.M<U>()", "U", "B").WithLocation(29, 14), // (30,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(30, 11), // (31,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(31, 11), // (31,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<B>.M<U>()' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<B>.M<U>()", "U", "B").WithLocation(31, 14), // (32,11): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<G>.M<H>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "G").WithArguments("C<T>", "T", "G").WithLocation(32, 11), // (33,14): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<H>.M<U>()' // C<H>.M<G>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<G>").WithArguments("C<H>.M<U>()", "U", "G").WithLocation(33, 14), // (34,11): error CS0310: 'I' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<I>.M<S>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "I").WithArguments("C<T>", "T", "I").WithLocation(34, 11), // (36,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.F<T>(D<T>)' // E.F(S.F<B>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("E.F<T>(D<T>)", "T", "B").WithLocation(36, 11), // (38,19): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(38, 19), // This invocation of E.F(S.F<C<B>>) is an extremely interesting one. // First off, obviously the type argument for S.F is prima facie wrong, so we give an error for that above. // But what about the overload resolution problem in error recovery? Even though the argument is bad we still // might want to try to get an overload resolution result. Thus we must infer a type for T in E.F<T>(D<T>). // We must do overload resolution on an invocation S.F<C<B>>(). Overload resolution succeeds; it has no reason // to fail. (Overload resolution would fail if a formal parameter type of S.F<C<B>>() did not satisfy one of its // constraints, but there are no formal parameters. Also, there are no constraints at all on T in S.F<T>.) // // Thus T in D<T> is inferred to be C<B>, and thus T in E.F<T> is inferred to be C<B>. // // Now we check to see whether E.F<C<B>>(D<C<B>>) is applicable. It is inapplicable because // B fails to meet the constraints of T in C<T>. (C<B> does not fail to meet the constraints // of T in D<T> because C<B> has a public default parameterless ctor.) // // Therefore E.F<C.B>(S.F<C<B>>) fails overload resolution. Why? Because B is not valid for T in C<T>. // (We cannot say that the constraints on T in E.F<T> is unmet because again, C<B> meets the // constraint; it has a ctor.) So that is the error we report. // // This is arguably a "cascading" error; we have already reported an error for C<B> when the // argument was bound. Normally we avoid reporting "cascading" errors in overload resolution by // saying that an erroneous argument is implicitly convertible to any formal parameter type; // thus we avoid an erroneous expression from causing overload resolution to make every // candidate method inapplicable. (Though it might cause overload resolution to fail by making // every candidate method applicable, causing an ambiguity!) But the overload resolution // error here is not caused by an argument *conversion* in the first place; the overload // resolution error is caused because *the deduced formal parameter type is illegal.* // // We might want to put some gear in place to suppress this cascading error. It is not // entirely clear what that machinery might look like. // (38,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("C<T>", "T", "B").WithLocation(38, 11), // (41,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.M<T>(object)' // o.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("E.M<T>(object)", "T", "B").WithLocation(41, 11), // (42,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'F<T, U>' // o = new F<A, B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("F<T, U>", "U", "B").WithLocation(42, 22)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied03() { var text = @"class A { } class B { private B() { } } class C<T, U> where U : struct { internal static void M<V>(V v) where V : new() { } void M() { A a = default(A); M(a); a.E(); B b = default(B); M(b); b.E(); T t = default(T); M(t); t.E(); U u1 = default(U); M(u1); u1.E(); U? u2 = null; M(u2); u2.E(); } } static class S { internal static void E<T>(this T t) where T : new() { } }"; CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (15,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(b); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "B").WithLocation(15, 9), // (16,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // b.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "B").WithLocation(16, 11), // (18,9): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(t); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "T").WithLocation(18, 9), // (19,11): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // t.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "T").WithLocation(19, 11) ); } /// <summary> /// Constraint errors within aliases. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied04() { var text = @"using NA = N.A; using NB = N.B; using CA = N.C<N.A>; using CB = N.C<N.B>; namespace N { using CAD = C<N.A>.D; using CBD = C<N.B>.D; class A { } // public (default) .ctor class B { private B() { } } // private .ctor class C<T> where T : new() { internal static void M<U>() where U : new() { } internal class D { private D() { } // private .ctor internal static void M<U>() where U : new() { } } } class E { static void M() { C<N.A>.M<N.B>(); C<NB>.M<NA>(); C<C<N.A>.D>.M<N.A>(); C<N.A>.D.M<N.B>(); C<N.B>.D.M<N.A>(); CA.M<N.B>(); CB.M<N.A>(); CAD.M<N.B>(); CBD.M<N.A>(); C<CAD>.M<N.A>(); C<CBD>.M<N.A>(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (4,7): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CB = N.C<N.B>; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CB").WithArguments("N.C<T>", "T", "N.B").WithLocation(4, 7), // (8,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CBD = C<N.B>.D; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.B").WithLocation(8, 11), // (24,20): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<N.A>.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(24, 20), // (25,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<NB>.M<NA>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "NB").WithArguments("N.C<T>", "T", "N.B").WithLocation(25, 15), // (26,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<C<N.A>.D>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C<N.A>.D").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(26, 15), // (27,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // C<N.A>.D.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(27, 22), // (28,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<N.B>.D.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "N.B").WithArguments("N.C<T>", "T", "N.B").WithLocation(28, 15), // (29,16): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // CA.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(29, 16), // (31,17): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // CAD.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(31, 17), // (33,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CAD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CAD").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(33, 15), // (34,15): error CS0310: 'C<B>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CBD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.C<N.B>.D").WithLocation(34, 15)); } /// <summary> /// Constructors with optional and params args /// should not be considered parameterless. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied05() { var text = @"class A { public A() { } } class B { public B(object o = null) { } } class C { public C(params object[] args) { } } class D<T> where T : new() { static void M() { D<A>.M(); D<B>.M(); D<C>.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (18,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("D<T>", "T", "B").WithLocation(18, 11), // (19,11): error CS0310: 'C' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C").WithArguments("D<T>", "T", "C").WithLocation(19, 11)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType01() { var source = @"class A { } class B { } class C<T> where T : A { } class D { static void M<T>() where T : A { } static void M() { object o = new C<B>(); M<B>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("C<T>", "A", "T", "B").WithLocation(9, 26), // (10,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'D.M<T>()'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<B>").WithArguments("D.M<T>()", "A", "T", "B").WithLocation(10, 9)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<T, V> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0311: The type 'V' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'V' to 'T'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "V").WithArguments("C<T, U>", "T", "U", "V").WithLocation(3, 12)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType03() { var source = @"interface I<T> where T : I<I<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0311: The type 'I<T>' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. There is no implicit reference conversion from 'I<T>' to 'I<I<I<T>>>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T").WithArguments("I<T>", "I<I<I<T>>>", "T", "I<T>").WithLocation(1, 13)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType04() { var source = @"interface IA<T> { } interface IB<T> where T : IA<T> { } class C<T1, T2, T3> where T1 : IB<object[]> where T2 : IB<T2> where T3 : IB<IB<T3>[]>, IA<T3> { }"; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0311: The type 'object[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'object[]' to 'IA<object[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T1").WithArguments("IB<T>", "IA<object[]>", "T", "object[]").WithLocation(3, 9), // (3,13): error CS0311: The type 'T2' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T2' to 'IA<T2>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T2").WithArguments("IB<T>", "IA<T2>", "T", "T2").WithLocation(3, 13), // (3,17): error CS0311: The type 'IB<T3>[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'IB<T3>[]' to 'IA<IB<T3>[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T3").WithArguments("IB<T>", "IA<IB<T3>[]>", "T", "IB<T3>[]").WithLocation(3, 17)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType05() { var source = @"namespace N { class C<T, U> where U : T { static object F() { return null; } static object G<V>() where V : T { return null; } static void M() { object o; o = C<int, object>.F(); o = N.C<int, int>.G<string>(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,24): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'object' to 'int'. // o = C<int, object>.F(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "object").WithArguments("N.C<T, U>", "int", "U", "object").WithLocation(16, 24), // (17,31): error CS0311: The type 'string' cannot be used as type parameter 'V' in the generic type or method 'C<int, int>.G<V>()'. There is no implicit reference conversion from 'string' to 'int'. // o = N.C<int, int>.G<string>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "G<string>").WithArguments("N.C<int, int>.G<V>()", "int", "V", "string").WithLocation(17, 31)); } [Fact] public void CS0312ERR_GenericConstraintNotSatisfiedNullableEnum() { var source = @"class A<T, U> where T : U { } class B<T> { static void M<U>() where U : T { } static void M() { object o = new A<int?, int>(); B<int>.M<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,26): error CS0312: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. The nullable type 'int?' does not satisfy the constraint of 'int'. // object o = new A<int?, int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "int?").WithArguments("A<T, U>", "int", "T", "int?").WithLocation(7, 26), // (8,16): error CS0312: The type 'int?' cannot be used as type parameter 'U' in the generic type or method 'B<int>.M<U>()'. The nullable type 'int?' does not satisfy the constraint of 'int'. // B<int>.M<int?>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "M<int?>").WithArguments("B<int>.M<U>()", "int", "U", "int?").WithLocation(8, 16)); } [Fact] public void CS0313ERR_GenericConstraintNotSatisfiedNullableInterface() { var source = @"interface I { } struct S : I { } class A<T> where T : I { } class B { static void M<T>() where T : I { } static void M() { object o = new A<S?>(); M<S?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "S?").WithArguments("A<T>", "I", "T", "S?").WithLocation(9, 26), // (10,9): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "M<S?>").WithArguments("B.M<T>()", "I", "T", "S?").WithLocation(10, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar01() { var source = @"class A { } class B<T> where T : A { } class C<T> where T : struct { static void M<U>() where U : A { } static void M() { object o = new B<T>(); M<T>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("B<T>", "A", "T", "T").WithLocation(8, 26), // (9,9): error CS0314: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'C<T>.M<U>()'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M<T>").WithArguments("C<T>.M<U>()", "A", "U", "T").WithLocation(9, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<V, U> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0314: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no boxing conversion or type parameter conversion from 'U' to 'V'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "V").WithArguments("C<T, U>", "V", "U", "U").WithLocation(3, 12)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar03() { var source = @"interface IA<T> where T : IB<T> { } interface IB<T> where T : IA<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IA<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IB<T>", "IA<T>", "T", "T").WithLocation(1, 14), // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IA<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IB<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IA<T>", "IB<T>", "T", "T").WithLocation(2, 14)); } [Fact] public void CS0315ERR_GenericConstraintNotSatisfiedValType() { var source = @"class A { } class B<T> where T : A { } struct S { } class C { static void M<T, U>() where U : A { } static void M() { object o = new B<S>(); M<int, double>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0315: The type 'S' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion from 'S' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "S").WithArguments("B<T>", "A", "T", "S").WithLocation(9, 26), // (10,9): error CS0315: The type 'double?' cannot be used as type parameter 'U' in the generic type or method 'C.M<T, U>()'. There is no boxing conversion from 'double?' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int, double>").WithArguments("C.M<T, U>()", "A", "U", "double").WithLocation(10, 9)); } [Fact] public void CS0316ERR_DuplicateGeneratedName() { var text = @" public class Test { public int this[int value] // CS0316 { get { return 1; } set { } } public int this[char @value] // CS0316 { get { return 1; } set { } } public int this[string value] // no error since no setter { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[char @value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "@value").WithArguments("value").WithLocation(10, 26), // (4,25): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[int value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "value").WithArguments("value").WithLocation(4, 25)); } [Fact] public void CS0403ERR_TypeVarCantBeNull() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M() { T1 t1 = null; T2 t2 = null; T3 t3 = null; T4 t4 = null; T5 t5 = null; T6 t6 = null; T7 t7 = null; } static T1 F1() { return null; } static T2 F2() { return null; } static T3 F3() { return null; } static T4 F4() { return null; } static T5 F5() { return null; } static T6 F6() { return null; } static T7 F7() { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // T1 t1 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (15,17): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // T3 t3 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (16,17): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // T4 t4 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (17,17): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // T5 t5 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (19,17): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // T7 t7 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7"), // (14,12): warning CS0219: The variable 't2' is assigned but its value is never used // T2 t2 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2"), // (18,12): warning CS0219: The variable 't6' is assigned but its value is never used // T6 t6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t6").WithArguments("t6"), // (21,29): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // static T1 F1() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (23,29): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // static T3 F3() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (24,29): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // static T4 F4() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (25,29): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // static T5 F5() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (27,29): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // static T7 F7() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7") ); } [WorkItem(539901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539901")] [Fact] public void CS0407ERR_BadRetType_01() { var text = @" public delegate int MyDelegate(); class C { MyDelegate d; public C() { d = new MyDelegate(F); // OK: F returns int d = new MyDelegate(G); // CS0407 - G doesn't return int } public int F() { return 1; } public void G() { } public static void Main() { C c1 = new C(); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); CreateCompilation(text).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); } [WorkItem(925899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925899")] [Fact] public void CS0407ERR_BadRetType_02() { var text = @" using System; class C { public static void Main() { var oo = new Func<object, object>(x => 1); var os = new Func<object, string>(oo); var ss = new Func<string, string>(oo); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (10,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); CreateCompilation(text).VerifyDiagnostics( // (10,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); } [WorkItem(539924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539924")] [Fact] public void CS0407ERR_BadRetType_03() { var text = @" delegate DerivedClass MyDerivedDelegate(DerivedClass x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base""); return x; } } public class DerivedClass : BaseClass { public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDerivedDelegate goo1 = null; goo1 += BaseClass.DelegatedMethod; goo1 += DerivedClass.DelegatedMethod; goo1(new DerivedClass()); } } "; CreateCompilation(text).VerifyDiagnostics( // (21,17): error CS0407: 'BaseClass BaseClass.DelegatedMethod(BaseClass)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "BaseClass.DelegatedMethod").WithArguments("BaseClass.DelegatedMethod(BaseClass)", "BaseClass")); } [WorkItem(3401, "DevDiv_Projects/Roslyn")] [Fact] public void CS0411ERR_CantInferMethTypeArgs01() { var text = @" class C { public void F<T>(T t) where T : C { } public static void Main() { C c = new C(); c.F(null); // CS0411 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantInferMethTypeArgs, Line = 11, Column = 11 } }); } [WorkItem(2099, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2099")] [Fact(Skip = "529560")] public void CS0411ERR_CantInferMethTypeArgs02() { var text = @" public class MemberInitializerTest { delegate void D<T>(); public static void GenericMethod<T>() { } public static void Run() { var genD = (D<int>)GenericMethod; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: The type arguments for method 'MemberInitializerTest.GenericMethod<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var genD = (D<int>)GenericMethod; Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "(D<int>)GenericMethod").WithArguments("MemberInitializerTest.GenericMethod<T>()") ); } [Fact] public void CS0412ERR_LocalSameNameAsTypeParam() { var text = @" using System; class C { // Parameter name is the same as method type parameter name public void G<T>(int T) // CS0412 { } public void F<T>() { // Method local variable name is the same as method type // parameter name double T = 0.0; // CS0412 Console.WriteLine(T); } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 14, Column = 16 } }); } [Fact] public void CS0413ERR_AsWithTypeVar() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = o as T1; o = o as T2; o = o as T3; o = o as T4; o = o as T5; o = o as T6; o = o as T7; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,13): error CS0413: The type parameter 'T1' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T1").WithArguments("T1").WithLocation(13, 13), // (15,13): error CS0413: The type parameter 'T3' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T3").WithArguments("T3").WithLocation(15, 13), // (16,13): error CS0413: The type parameter 'T4' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T4").WithArguments("T4").WithLocation(16, 13), // (17,13): error CS0413: The type parameter 'T5' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T5").WithArguments("T5").WithLocation(17, 13), // (19,13): error CS0413: The type parameter 'T7' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T7").WithArguments("T7").WithLocation(19, 13)); } [Fact] public void CS0417ERR_NewTyvarWithArgs01() { var source = @"struct S<T> where T : new() { T F(object o) { return new T(o); } U G<U, V>(object o) where U : new() where V : struct { return new U(new V(o)); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(o)").WithArguments("T").WithLocation(5, 16), // (11,16): error CS0417: 'U': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new U(new V(o))").WithArguments("U").WithLocation(11, 16), // (11,22): error CS0417: 'V': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new V(o)").WithArguments("V").WithLocation(11, 22)); } [Fact] public void CS0417ERR_NewTyvarWithArgs02() { var source = @"class C { public C() { } public C(object o) { } static void M<T>() where T : C, new() { new T(); new T(null); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(null)").WithArguments("T").WithLocation(8, 9)); } [Fact] public void CS0428ERR_MethGrpToNonDel() { var text = @" namespace ConsoleApplication1 { class Program { delegate int Del1(); delegate object Del2(); static void Main(string[] args) { ExampleClass ec = new ExampleClass(); int i = ec.Method1; Del1 d1 = ec.Method1; i = ec.Method1(); ec = ExampleClass.Method2; Del2 d2 = ExampleClass.Method2; ec = ExampleClass.Method2(); } } public class ExampleClass { public int Method1() { return 1; } public static ExampleClass Method2() { return null; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 15, Column = 31 }}); } [Fact, WorkItem(528649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528649")] public void CS0431ERR_ColColWithTypeAlias() { var text = @" using AliasC = C; class C { public class Goo { } } class Test { class C { } static int Main() { AliasC::Goo goo = new AliasC::Goo(); return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC"), Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0445ERR_UnboxNotLValue() { var text = @" namespace ConsoleApplication1 { // CS0445.CS class UnboxingTest { public static void Main() { Point p = new Point(); p.x = 1; p.y = 5; object obj = p; // Generates CS0445: ((Point)obj).x = 2; } } public struct Point { public int x; public int y; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnboxNotLValue, Line = 15, Column = 13 } }); } [Fact] public void CS0446ERR_AnonMethGrpInForEach() { var text = @" class Tester { static void Main() { int[] intArray = new int[5]; foreach (int i in M) { } // CS0446 } static void M() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethGrpInForEach, Line = 7, Column = 27 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0452_GenericConstraintError_HasHigherPriorityThanMethodOverloadError() { var code = @" class Code { void GenericMethod<T>(int i) where T: class => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<int>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (9,9): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Code.GenericMethod<T>(int)' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "GenericMethod<int>").WithArguments("Code.GenericMethod<T>(int)", "T", "int").WithLocation(9, 9)); } [Fact] public void CS0457ERR_AmbigUDConv() { var text = @" public class A { } public class G0 { } public class G1<R> : G0 { } public class H0 { public static implicit operator G0(H0 h) { return new G0(); } } public class H1<R> : H0 { public static implicit operator G1<R>(H1<R> h) { return new G1<R>(); } } public class Test { public static void F0(G0 g) { } public static void Main() { H1<A> h1a = new H1<A>(); F0(h1a); // CS0457 } } "; CreateCompilation(text).VerifyDiagnostics( // (24,10): error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' Diagnostic(ErrorCode.ERR_AmbigUDConv, "h1a").WithArguments("H1<A>.implicit operator G1<A>(H1<A>)", "H0.implicit operator G0(H0)", "H1<A>", "G0")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void AddrOnReadOnlyLocal() { var text = @" class A { public unsafe void M1() { int[] ints = new int[] { 1, 2, 3 }; foreach (int i in ints) { int *j = &i; } fixed (int *i = &_i) { int **j = &i; } } private int _i = 0; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0463ERR_DecConstError() { var text = @" using System; class MyClass { public static void Main() { const decimal myDec = 79000000000000000000000000000.0m + 79000000000000000000000000000.0m; // CS0463 Console.WriteLine(myDec.ToString()); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DecConstError, Line = 7, Column = 31 } }); } [WorkItem(543272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543272")] [Fact] public void CS0463ERR_DecConstError_02() { var text = @" class MyClass { public static void Main() { decimal x1 = decimal.MaxValue + 1; // CS0463 decimal x2 = decimal.MaxValue + decimal.One; // CS0463 decimal x3 = decimal.MinValue - decimal.One; // CS0463 decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x1 = decimal.MaxValue + 1; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + 1"), // (7,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x2 = decimal.MaxValue + decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + decimal.One"), // (8,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x3 = decimal.MinValue - decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue - decimal.One"), // (9,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue + decimal.MinusOne"), // (10,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue - decimal.MinValue")); } [Fact()] public void CS0471ERR_TypeArgsNotAllowedAmbig() { var text = @" class Test { public void F(bool x, bool y) {} public void F1() { int a = 1, b = 2, c = 3; F(a<b, c>(3)); // CS0471 // To resolve, try the following instead: // F((a<b), c>(3)); } } "; //Dev11 used to give 'The {1} '{0}' is not a generic method. If you intended an expression list, use parentheses around the &lt; expression.' //Roslyn will be satisfied with something less helpful. var noWarns = new Dictionary<string, ReportDiagnostic>(); noWarns.Add(MessageProvider.Instance.GetIdForErrorCode(219), ReportDiagnostic.Suppress); CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(noWarns)).VerifyDiagnostics( // (8,13): error CS0118: 'b' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "b").WithArguments("b", "variable", "type"), // (8,16): error CS0118: 'c' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "c").WithArguments("c", "variable", "type"), // (8,11): error CS0307: The variable 'a' cannot be used with type arguments // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "a<b, c>").WithArguments("a", "variable")); } [Fact] public void CS0516ERR_RecursiveConstructorCall() { var text = @" namespace x { public class clx { public clx() : this() // CS0516 { } public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0516: Constructor 'x.clx.clx()' cannot call itself Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "this").WithArguments("x.clx.clx()")); } [WorkItem(751825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751825")] [Fact] public void Repro751825() { var text = @" public class A : A<int> { public A() : base() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,18): error CS0308: The non-generic type 'A' cannot be used with type arguments // public class A : A<int> Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type"), // (4,18): error CS0516: Constructor 'A.A()' cannot call itself // public A() : base() { } Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "base").WithArguments("A.A()")); } [WorkItem(366, "https://github.com/dotnet/roslyn/issues/366")] [Fact] public void IndirectConstructorCycle() { var text = @" public class A { public A() : this(1) {} public A(int x) : this(string.Empty) {} public A(string s) : this(1) {} public A(long l) : this(double.MaxValue) {} public A(double d) : this(char.MaxValue) {} public A(char c) : this(long.MaxValue) {} public A(short s) : this() {} } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0768: Constructor 'A.A(string)' cannot call itself through another constructor // public A(string s) : this(1) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(1)").WithArguments("A.A(string)").WithLocation(6, 24), // (9,22): error CS0768: Constructor 'A.A(char)' cannot call itself through another constructor // public A(char c) : this(long.MaxValue) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(long.MaxValue)").WithArguments("A.A(char)").WithLocation(9, 22) ); } [Fact] public void CS0517ERR_ObjectCallingBaseConstructor() { var text = @"namespace System { public class Void { } //just need the type to be defined public class Object { public Object() : base() { } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (7,16): error CS0517: 'object' has no base class and cannot call a base constructor Diagnostic(ErrorCode.ERR_ObjectCallingBaseConstructor, "Object").WithArguments("object")); } [Fact] public void CS0522ERR_StructWithBaseConstructorCall() { var text = @" public class clx { public clx(int i) { } public static void Main() { } } public struct cly { public cly(int i):base(0) // CS0522 // try the following line instead // public cly(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,11): error CS0522: 'cly': structs cannot call base class constructors Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "cly").WithArguments("cly")); } [Fact] public void CS0543ERR_EnumeratorOverflow01() { var source = @"enum E { A = int.MaxValue - 1, B, C, // CS0543 D, E = C, F, G = B, H, // CS0543 I } "; CreateCompilation(source).VerifyDiagnostics( // (5,5): error CS0543: 'E.C': the enumerator value is too large to fit in its type // C, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "C").WithArguments("E.C").WithLocation(5, 5), // (10,5): error CS0543: 'E.H': the enumerator value is too large to fit in its type // H, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "H").WithArguments("E.H").WithLocation(10, 5)); } [Fact] public void CS0543ERR_EnumeratorOverflow02() { var source = @"namespace N { enum E : byte { A = 255, B, C } enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } enum G : int { X = int.MinValue, Y = X - 1, Z } } "; CreateCompilation(source).VerifyDiagnostics( // (3,30): error CS0543: 'E.B': the enumerator value is too large to fit in its type // enum E : byte { A = 255, B, C } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "B").WithArguments("N.E.B").WithLocation(3, 30), // (5,42): error CS0220: The operation overflows at compile time in checked mode // enum G : int { X = int.MinValue, Y = X - 1, Z } Diagnostic(ErrorCode.ERR_CheckedOverflow, "X - 1").WithLocation(5, 42), // (4,57): error CS0543: 'F.D': the enumerator value is too large to fit in its type // enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "D").WithArguments("N.F.D").WithLocation(4, 57)); } [Fact] public void CS0543ERR_EnumeratorOverflow03() { var source = @"enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } "; CreateCompilation(source).VerifyDiagnostics( // (3,84): error CS0543: 'S32.J': the enumerator value is too large to fit in its type // enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S32.J").WithLocation(3, 84), // (4,87): error CS0543: 'S64.J': the enumerator value is too large to fit in its type // enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S64.J").WithLocation(4, 87), // (7,61): error CS0543: 'U32.G': the enumerator value is too large to fit in its type // enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U32.G").WithLocation(7, 61), // (6,65): error CS0543: 'U16.G': the enumerator value is too large to fit in its type // enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U16.G").WithLocation(6, 65), // (5,60): error CS0543: 'U8.G': the enumerator value is too large to fit in its type // enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U8.G").WithLocation(5, 60), // (2,90): error CS0543: 'S16.J': the enumerator value is too large to fit in its type // enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S16.J").WithLocation(2, 90), // (1,89): error CS0543: 'S8.J': the enumerator value is too large to fit in its type // enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S8.J").WithLocation(1, 89), // (8,63): error CS0543: 'U64.G': the enumerator value is too large to fit in its type // enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U64.G").WithLocation(8, 63)); } [Fact] public void CS0543ERR_EnumeratorOverflow04() { string source = string.Format( @"enum A {0} enum B : byte {1} enum C : byte {2} enum D : sbyte {3}", CreateEnumValues(300, "E"), CreateEnumValues(256, "E"), CreateEnumValues(300, "E"), CreateEnumValues(300, "E", sbyte.MinValue)); CreateCompilation(source).VerifyDiagnostics( // (3,1443): error CS0543: 'C.E256': the enumerator value is too large to fit in its type // enum C : byte { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("C.E256").WithLocation(3, 1443), // (4,1451): error CS0543: 'D.E256': the enumerator value is too large to fit in its type // enum D : sbyte { E0 = -128, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("D.E256").WithLocation(4, 1451)); } // Create string "{ E0, E1, ..., En }" private static string CreateEnumValues(int count, string prefix, int? initialValue = null) { var builder = new System.Text.StringBuilder("{ "); for (int i = 0; i < count; i++) { builder.Append(prefix); builder.Append(i); if ((i == 0) && (initialValue != null)) { builder.AppendFormat(" = {0}", initialValue.Value); } builder.Append(", "); } builder.Append(" }"); return builder.ToString(); } // CS0570 --> Symbols\OverriddenOrHiddenMembersTests.cs [Fact] public void CS0571ERR_CantCallSpecialMethod01() { var source = @"class C { protected virtual object P { get; set; } static object Q { get; set; } void M(D d) { this.set_P(get_Q()); D.set_Q(d.get_P()); ((this.get_P))(); } } class D : C { protected override object P { get { return null; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,20): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("C.Q.get").WithLocation(7, 20), // (7,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(7, 14), // (8,19): error CS0571: 'D.P.get': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("D.P.get").WithLocation(8, 19), // (8,11): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("C.Q.set").WithLocation(8, 11), // (9,16): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // ((this.get_P))(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("C.P.get").WithLocation(9, 16)); // CONSIDER: Dev10 reports 'C.P.get' for the fourth error. Roslyn reports 'D.P.get' // because it is in the more-derived type and because Binder.LookupMembersInClass // calls MergeHidingLookups(D.P.get, C.P.get) with both arguments non-viable // (i.e. keeps current, since new value isn't better). } [Fact] public void CS0571ERR_CantCallSpecialMethod02() { var source = @"using System; namespace A.B { class C { object P { get; set; } static object Q { get { return 0; } set { } } void M(C c) { Func<object> f = get_P; f = C.get_Q; Action<object> a = c.set_P; a = set_Q; } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // Func<object> f = get_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.B.C.P.get").WithLocation(10, 30), // (11,19): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // f = C.get_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("A.B.C.Q.get").WithLocation(11, 19), // (12,34): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // Action<object> a = c.set_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("A.B.C.P.set").WithLocation(12, 34), // (13,17): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // a = set_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("A.B.C.Q.set").WithLocation(13, 17)); } /// <summary> /// No errors should be reported if method with /// accessor name is defined in different class. /// </summary> [Fact] public void CS0571ERR_CantCallSpecialMethod03() { var source = @"class A { public object get_P() { return null; } } class B : A { public object P { get; set; } void M() { object o = this.P; o = this.get_P(); } } class C { void M(B b) { object o = b.P; o = b.get_P(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact()] public void CS0571ERR_CantCallSpecialMethod04() { var compilation = CreateCompilation( @"public class MyClass { public static MyClass operator ++(MyClass c) { return null; } public static void M() { op_Increment(null); // CS0571 } } ").VerifyDiagnostics( // (9,9): error CS0571: 'MyClass.operator ++(MyClass)': cannot explicitly call operator or accessor // op_Increment(null); // CS0571 Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Increment").WithArguments("MyClass.operator ++(MyClass)")); } [Fact] public void CS0571ERR_CantCallSpecialMethod05() { var source = @" using System; public class C { public static void M() { IntPtr.op_Addition(default(IntPtr), 0); IntPtr.op_Subtraction(default(IntPtr), 0); IntPtr.op_Equality(default(IntPtr), default(IntPtr)); IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); IntPtr.op_Explicit(0); } } "; CreateCompilation(source).VerifyDiagnostics( // (7,16): error CS0571: 'IntPtr.operator +(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Addition(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Addition").WithArguments("System.IntPtr.operator +(System.IntPtr, int)").WithLocation(7, 16), // (8,16): error CS0571: 'IntPtr.operator -(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Subtraction(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Subtraction").WithArguments("System.IntPtr.operator -(System.IntPtr, int)").WithLocation(8, 16), // (9,16): error CS0571: 'IntPtr.operator ==(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Equality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Equality").WithArguments("System.IntPtr.operator ==(System.IntPtr, System.IntPtr)").WithLocation(9, 16), // (10,16): error CS0571: 'IntPtr.operator !=(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Inequality").WithArguments("System.IntPtr.operator !=(System.IntPtr, System.IntPtr)").WithLocation(10, 16), // (11,16): error CS0571: 'IntPtr.explicit operator IntPtr(int)': cannot explicitly call operator or accessor // IntPtr.op_Explicit(0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Explicit").WithArguments("System.IntPtr.explicit operator System.IntPtr(int)").WithLocation(11, 16)); } [Fact] public void CS0572ERR_BadTypeReference() { var text = @" using System; class C { public class Inner { public static int v = 9; } } class D : C { public static void Main() { C cValue = new C(); Console.WriteLine(cValue.Inner.v); // CS0572 // try the following line instead // Console.WriteLine(C.Inner.v); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadTypeReference, Line = 16, Column = 32 } }); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public class iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny() { var text = @" public class Test { public System.TypedReference[] x; public System.RuntimeArgumentHandle[][] y; } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (4,12): error CS0611: Array elements cannot be of type 'System.TypedReference' // public System.TypedReference[] x; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(4, 12), // (5,12): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // public System.RuntimeArgumentHandle[][] y; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(5, 12)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny_1() { var text = @"using System; class C { static void M() { var x = new[] { new ArgIterator() }; var y = new[] { new TypedReference() }; var z = new[] { new RuntimeArgumentHandle() }; } }"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (6,17): error CS0611: Array elements cannot be of type 'System.ArgIterator' // var x = new[] { new ArgIterator() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new ArgIterator() }").WithArguments("System.ArgIterator").WithLocation(6, 17), // (7,17): error CS0611: Array elements cannot be of type 'System.TypedReference' // var y = new[] { new TypedReference() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new TypedReference() }").WithArguments("System.TypedReference").WithLocation(7, 17), // (8,17): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // var z = new[] { new RuntimeArgumentHandle() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new RuntimeArgumentHandle() }").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 17)); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0619ERR_DeprecatedSymbolStr() { var text = @" using System; namespace a { [Obsolete] class C1 { } [Obsolete(""Obsolescence message"", true)] interface I1 { } public class CI1 : I1 { } public class MainClass { public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,24): error CS0619: 'a.I1' is obsolete: 'Obsolescence message' // public class CI1 : I1 { } Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "I1").WithArguments("a.I1", "Obsolescence message") ); } [Fact] public void CS0622ERR_ArrayInitToNonArrayType() { var text = @" public class Test { public static void Main () { Test t = { new Test() }; // CS0622 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitToNonArrayType, Line = 6, Column = 18 } }); } [Fact] public void CS0623ERR_ArrayInitInBadPlace() { var text = @" class X { public void goo(int a) { int[] x = { { 4 } }; //CS0623 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitInBadPlace, Line = 6, Column = 21 } }); } [Fact] public void CS0631ERR_IllegalRefParam() { var compilation = CreateCompilation( @"interface I { object this[ref object index] { get; set; } } class C { internal object this[object x, out object y] { get { y = null; return null; } } } struct S { internal object this[out int x, out int y] { set { x = 0; y = 0; } } }"); compilation.VerifyDiagnostics( // (3,17): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 17), // (7,36): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(7, 36), // (11,26): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 26), // (11,37): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 37)); } [WorkItem(529305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529305")] [Fact()] public void CS0664ERR_LiteralDoubleCast() { var text = @" class Example { static void Main() { // CS0664, because 1.0 is interpreted as a double: decimal d1 = 1.0; float f1 = 2.0; } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,22): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type // decimal d1 = 1.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "1.0").WithArguments("M", "decimal").WithLocation(7, 22), // (8,20): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type // float f1 = 2.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "2.0").WithArguments("F", "float").WithLocation(8, 20), // (7,17): warning CS0219: The variable 'd1' is assigned but its value is never used // decimal d1 = 1.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d1").WithArguments("d1").WithLocation(7, 17), // (8,15): warning CS0219: The variable 'f1' is assigned but its value is never used // float f1 = 2.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "f1").WithArguments("f1").WithLocation(8, 15)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType() { CreateCompilation(@" class C { void x = default(void); }").VerifyDiagnostics( // (4,22): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (4,5): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void")); } [Fact] public void CS0670ERR_FieldCantHaveVoidType_Var() { CreateCompilationWithMscorlib45(@" var x = default(void); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,17): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (2,1): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var")); } [WorkItem(538016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538016")] [Fact] public void CS0687ERR_AliasQualAsExpression() { var text = @" using M = Test; using System; public class Test { public static int x = 77; public static void Main() { Console.WriteLine(M::x); // CS0687 } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "M").WithArguments("M") ); } [Fact] public void CS0704ERR_LookupInTypeVariable() { var text = @"using System; class A { internal class B : Attribute { } internal class C<T> { } } class D<T> where T : A { class E : T.B { } interface I<U> where U : T.B { } [T.B] static object M<U>() { T.C<object> b1 = new T.C<object>(); T<U>.B b2 = null; b1 = default(T.B); object o = typeof(T.C<A>); o = o as T.B; return b1; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,15): error CS0704: Cannot do member lookup in 'T' because it is a type parameter class E : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (10,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // interface I<U> where U : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (11,6): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // [T.B] Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (14,9): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (14,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (15,9): error CS0307: The type parameter 'T' cannot be used with type arguments // T<U>.B b2 = null; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter"), // (16,22): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // b1 = default(T.B); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (17,27): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // object o = typeof(T.C<A>); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<A>").WithArguments("T"), // (18,18): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // o = o as T.B; Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T") ); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" public static class SC { } public class CMain { public static void Main() { SC sc = new SC(); // CS0712 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_InstantiatingStaticClass, Line = 10, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VarDeclIsStaticClass, Line = 10, Column = 9 }}); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" public static class SC { static void F() { } } public class Test { public static void Main() { object o = new object(); System.Console.WriteLine((SC)o); // CS0716 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ConvertToStaticClass, Line = 12, Column = 34 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0718_StaticClassError_HasHigherPriorityThanMethodOverloadError() { var code = @" static class StaticClass { } class Code { void GenericMethod<T>(int i) => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<StaticClass>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,9): error CS0718: 'StaticClass': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "GenericMethod<StaticClass>").WithArguments("StaticClass").WithLocation(11, 9)); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Locals() { CreateCompilation( @"static class SC { static void M() { SC sc = null; // CS0723 N(sc); var sc2 = new SC(); } static void N(object o) { } }").VerifyDiagnostics( // (5,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "SC").WithArguments("SC"), // (7,19): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC"), // (7,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "var").WithArguments("SC")); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Fields() { CreateCompilationWithMscorlib45(@" static class SC {} var sc2 = new SC(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (4,5): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "sc2").WithArguments("SC"), // (4,11): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC")); } [Fact] public void CS0724ERR_BadEmptyThrowInFinally() { var text = @" using System; class X { static void Test() { try { throw new Exception(); } catch { try { } finally { throw; // CS0724 } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw").WithLocation(19, 17)); } [Fact, WorkItem(1040213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040213")] public void CS0724ERR_BadEmptyThrowInFinally_Nesting() { var text = @" using System; class X { static void Test(bool b) { try { throw new Exception(); } catch { try { } finally { if (b) throw; // CS0724 try { throw; // CS0724 } catch { throw; // OK } finally { throw; // CS0724 } } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw")); } [Fact] public void CS0747ERR_InvalidInitializerElementInitializer() { var text = @" using System.Collections.Generic; public class C { public static int Main() { var t = new List<int> { Capacity = 2, 1 }; // CS0747 return 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "1")); } [Fact] public void CS0762ERR_PartialMethodToDelegate() { var text = @" public delegate void TestDel(); public partial class C { partial void Part(); public static int Main() { C c = new C(); TestDel td = new TestDel(c.Part); // CS0762 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodToDelegate, Line = 11, Column = 38 } }); } [Fact] public void CS0765ERR_PartialMethodInExpressionTree() { var text = @" using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; public delegate void dele(); public class ConClass { [Conditional(""CONDITION"")] public static void TestMethod() { } } public partial class PartClass : IEnumerable { List<object> list = new List<object>(); partial void Add(int x); public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } static void Main() { Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (30,71): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "1"), // (30,74): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "2"), // (31,44): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "ConClass.TestMethod()")); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Local() { CreateCompilation(@" class Test { public static void Main() { var m = Main; var d = s => -1; // CS8917 var e = (string s) => 0; var p = null;//CS0815 var del = delegate(string a) { return -1; }; var v = M(); // CS0815 } static void M() {} }").VerifyDiagnostics( // (7,17): error CS8917: The delegate type could not be inferred. // var d = s => -1; // CS8917 Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "s => -1").WithLocation(7, 17), // (9,13): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null;//CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>").WithLocation(9, 13), // (11,13): error CS0815: Cannot assign void to an implicitly-typed variable // var v = M(); // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "v = M()").WithArguments("void").WithLocation(11, 13)); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Field() { CreateCompilationWithMscorlib45(@" static void M() {} var m = M; var d = s => -1; var e = (string s) => 0; var p = null; var del = delegate(string a) { return -1; }; var v = M(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (5,9): error CS8917: The delegate type could not be inferred. // var d = s => -1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "s => -1").WithLocation(5, 9), // (7,5): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>").WithLocation(7, 5), // (9,1): error CS0670: Field cannot have void type // var v = M(); Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var").WithLocation(9, 1)); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer() { var text = @" class A { public static int Main() { var a; // CS0818 return -1; } }"; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, Line = 6, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVar, Line = 6, Column = 13, IsWarning = true }}); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer_Fields() { CreateCompilationWithMscorlib45(@" var a; // CS0818 ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0818: Implicitly-typed variables must be initialized Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "a")); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Locals() { var text = @" class A { public static int Main() { var a = 3, b = 2; // CS0819 return -1; } } "; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 13, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 20, IsWarning = true }}); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Fields() { CreateCompilationWithMscorlib45(@" var goo = 4, bar = 4.5; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,1): error CS0819: Implicitly-typed fields cannot have multiple declarators Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var")); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer() { var text = @" class G { public static int Main() { var a = { 1, 2, 3 }; //CS0820 return -1; } }"; // In the native compilers this code produces two errors, both // "you can't assign an array initializer to an implicitly typed local" and // "you can only use an array initializer to assign to an array type". // It seems like the first error ought to prevent the second. In Roslyn // we only produce the first error. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, Line = 6, Column = 13 }}); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer_Fields() { CreateCompilationWithMscorlib45(@" var y = { 1, 2, 3 }; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "y = { 1, 2, 3 }")); } [Fact] public void CS0821ERR_ImplicitlyTypedLocalCannotBeFixed() { var text = @" class A { static int x; public static int Main() { unsafe { fixed (var p = &x) { } } return -1; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,24): error CS0821: Implicitly-typed local variables cannot be fixed // fixed (var p = &x) { } Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x")); } [Fact] public void CS0822ERR_ImplicitlyTypedLocalCannotBeConst() { var text = @" class A { public static void Main() { const var x = 0; // CS0822.cs const var y = (int?)null + x; } }"; // In the dev10 compiler, the second line reports both that "const var" is illegal // and that the initializer must be a valid constant. This seems a bit odd, so // in Roslyn we just report the first error. Let the user sort out whether they // meant it to be a constant or a variable, and then we can tell them if its a // bad constant. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): error CS0822: Implicitly-typed variables cannot be constant // const var x = 0; // CS0822.cs Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var x = 0").WithLocation(6, 15), // (7,15): error CS0822: Implicitly-typed variables cannot be constant // const var y = (int?)null + x; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var y = (int?)null + x").WithLocation(7, 15), // (7,23): warning CS0458: The result of the expression is always 'null' of type 'int?' // const var y = (int?)null + x; Diagnostic(ErrorCode.WRN_AlwaysNull, "(int?)null + x").WithArguments("int?").WithLocation(7, 23) ); } [Fact] public void CS0822ERR_ImplicitlyTypedVariableCannotBeConst_Fields() { CreateCompilationWithMscorlib45(@" const var x = 0; // CS0822.cs ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,7): error CS0822: Implicitly-typed variables cannot be constant Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields() { CreateCompilationWithMscorlib45(@" void goo(var arg) { } var goo(int arg) { return 2; } ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (2,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields2() { CreateCompilationWithMscorlib45(@" T goo<T>() { return default(T); } goo<var>(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,5): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact()] public void CS0826ERR_ImplicitlyTypedArrayNoBestType() { var text = @" public class C { delegate void D(); public static void M1() {} public static void M2(int x) {} public static int M3() { return 1; } public static int M4(int x) { return x; } public static int Main() { var z = new[] { 1, ""str"" }; // CS0826 char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826 var a = new [] {}; // CS0826 byte b = 3; var arr = new [] {b, c}; // CS0826 var a1 = new [] {null}; // CS0826 var a2 = new [] {null, null, null}; // CS0826 D[] l1 = new [] {x=>x+1}; // CS0826 D[] l2 = new [] {x=>x+1, x=>{return x + 1;}, (int x)=>x+1, (int x)=>{return x + 1;}, (x, y)=>x + y, ()=>{return 1;}}; // CS0826 D[] d1 = new [] {delegate {}}; // CS0826 D[] d2 = new [] {delegate {}, delegate (){}, delegate {return 1;}, delegate {return;}, delegate(int x){}, delegate(int x){return x;}, delegate(int x, int y){return x + y;}}; // CS0826 var m = new [] {M1, M2, M3, M4}; // CS0826 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 12, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 20, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 22, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 25, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 27, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 28, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 30, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 31, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 33, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 36, Column = 17 }}); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue() { var text = @" public class C { public static int Main() { var c = new { p1 = null }; // CS0828 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_2() { var text = @" public class C { public static void Main() { var c = new { p1 = Main }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_3() { var text = @" public class C { public static void Main() { var c = new { p1 = Main() }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_4() { var text = @" public class C { public static void Main() { var c = new { p1 = ()=>3 }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_5() { var text = @" public class C { public static void Main() { var c = new { p1 = delegate { return 1; } // CS0828 }; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 8, Column = 13 } }); } [Fact] public void CS0831ERR_ExpressionTreeContainsBaseAccess() { var text = @" using System; using System.Linq.Expressions; public class A { public virtual int BaseMethod() { return 1; } } public class C : A { public override int BaseMethod() { return 2; } public int Test(C c) { Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,41): error CS0831: An expression tree may not contain a base access // Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, "base") ); } [Fact] public void CS0832ERR_ExpressionTreeContainsAssignment() { var text = @" using System; using System.Linq.Expressions; public class C { public static int Main() { Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Expression<Func<int, int>> e2 = x => x = 5; // CS0843 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x += 5"), // (10,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e2 = x => x = 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x = 5") ); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName() { var text = @" public class C { public static int Main() { var c = new { p1 = 1, p1 = 2 }; // CS0833 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_2() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 return 1; } static string Prop { get; set; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_3() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 + CS0828 return 1; } static string Prop() { return null; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 }}); } [Fact] public void CS0834ERR_StatementLambdaToExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, int>> e = x => { return x; }; // CS0834 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree // Expression<Func<int, int>> e = x => { return x; }; // CS0834 Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, "x => { return x; }") ); } [Fact] public void CS0835ERR_ExpressionTreeMustHaveDelegate() { var text = @" using System.Linq.Expressions; public class Myclass { public static int Main() { Expression<int> e = x => x + 1; // CS0835 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { LinqAssemblyRef }, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExpressionTreeMustHaveDelegate, Line = 8, Column = 29 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable() { var text = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class MyClass : Attribute { public MyClass(object obj) { } } [MyClass(new { })] // CS0836 public class ClassGoo { } public class Test { public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 11, Column = 10 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable2() { var text = @" public class Test { const object x = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 4, Column = 22 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable3() { var text = @" public class Test { static object y = new { }; private object x = new { }; public static int Main() { return 0; } } "; // NOTE: Actually we assert that #836 is NOT generated DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable4() { var text = @" public class Test { public static int Main(object x = new { }) { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueMustBeConstant, Line = 4, Column = 39 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable5() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable6() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 static object y = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0837ERR_LambdaInIsAs() { var text = @" namespace TestNamespace { public delegate void Del(); class Test { static int Main() { bool b1 = (() => { }) is Del; // CS0837 bool b2 = delegate() { } is Del;// CS0837 Del d1 = () => { } as Del; // CS0837 Del d2 = delegate() { } as Del; // CS0837 return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(5)).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration01() { CreateCompilation( @"class C { static void M() { j = 5; // CS0841 int j; // To fix, move this line up. } } ") // The native compiler just produces the "var used before decl" error; the Roslyn // compiler runs the flow checking pass even if the initial binding failed. We // might consider turning off flow checking if the initial binding failed, and // removing the warning here. .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "j").WithArguments("j"), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration02() { CreateCompilation( @"class C { static void M() { int a = b, b = 0, c = a; for (int x = y, y = 0; ; ) { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration03() { // It is a bit unfortunate that we produce "can't use variable before decl" here // when the variable is being used after the decl. Perhaps we should generate // a better error? CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { var x = N(out x); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration04() { var systemRef = Net451.System; CreateCompilationWithMscorlib40AndSystemCore( @"using System.Collections.Generic; class Base { int i; } class Derived : Base { int j; } class C { public static void Main() { HashSet<Base> set1 = new HashSet<Base>(); foreach (Base b in set1) { Derived d = b as Derived; Base b = null; } } } ", new List<MetadataReference> { systemRef }) .VerifyDiagnostics( // (18,25): error CS0841: Cannot use local variable 'b' before it is declared // Derived d = b as Derived; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), // (19,18): error CS0136: A local or parameter named 'b' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Base b = null; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "b").WithArguments("b"), // (4,9): warning CS0169: The field 'Base.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("Base.i"), // (8,9): warning CS0169: The field 'Derived.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("Derived.j")); } /// <summary> /// No errors using statics before declaration. /// </summary> [Fact] public void StaticUsedBeforeDeclaration() { var text = @"class C { static int F = G + 2; static int G = F + 1; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0843ERR_UnassignedThisAutoProperty() { var text = @" struct S { public int AIProp { get; set; } public S(int i) { } //CS0843 } class Test { static int Main() { return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnassignedThisAutoProperty, Line = 5, Column = 12 } }); } [Fact] public void CS0844ERR_VariableUsedBeforeDeclarationAndHidesField() { var text = @" public class MyClass { int num; public void TestMethod() { num = 5; // CS0844 int num = 6; System.Console.WriteLine(num); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,9): error CS0844: Cannot use local variable 'num' before it is declared. The declaration of the local variable hides the field 'MyClass.num'. // num = 5; // CS0844 Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "num").WithArguments("num", "MyClass.num"), // (4,9): warning CS0169: The field 'MyClass.num' is never used // int num; Diagnostic(ErrorCode.WRN_UnreferencedField, "num").WithArguments("MyClass.num") ); } [Fact] public void CS0845ERR_ExpressionTreeContainsBadCoalesce() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Expression<Func<object>> e = () => null ?? ""x""; // CS0845 } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,48): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side // Expression<Func<object>> e = () => null ?? "x"; // CS0845 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null") ); } [WorkItem(3717, "DevDiv_Projects/Roslyn")] [Fact] public void CS0846ERR_ArrayInitializerExpected() { var text = @"public class Myclass { public static void Main() { int[,] a = new int[,] { 1 }; // error } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitializerExpected, Line = 5, Column = 33 } }); } [Fact] public void CS0847ERR_ArrayInitializerIncorrectLength() { var text = @" public class Program { public static void Main(string[] args) { int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected ar0[0] = ar1[0]; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,31): error CS0847: An array initializer of length '0' is expected // int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{0}").WithArguments("0").WithLocation(6, 31), // (7,31): error CS0847: An array initializer of length '3' is expected // int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{}").WithArguments("3").WithLocation(7, 31)); } [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(minSessions:5); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0853: An expression tree may not contain a named argument specification // Expression<dg> myET = x => Index(minSessions:5); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "Index(minSessions:5)").WithLocation(10, 40) ); } [WorkItem(545063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545063")] [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument02() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class A { static void Main() { Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,41): error CS0853: An expression tree may not contain a named argument specification // Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "new List<int> { 1 } [index: 0]").WithLocation(10, 41) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // Expression<dg> myET = x => Index(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "Index()").WithLocation(10, 40) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument02() { var text = @"using System; using System.Linq.Expressions; class A { internal object this[int x, int y = 2] { get { return null; } } } class B { internal object this[int x, int y = 2] { set { } } } class C { static void M(A a, B b) { Expression<Func<object>> e1; e1 = () => a[0]; e1 = () => a[1, 2]; Expression<Action> e2; e2 = () => b[3] = null; e2 = () => b[4, 5] = null; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (22,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "a[0]").WithLocation(22, 20), // (25,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[3] = null").WithLocation(25, 20), // (25,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "b[3]").WithLocation(25, 20), // (26,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[4, 5] = null").WithLocation(26, 20)); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument03() { var text = @"using System; using System.Collections; using System.Linq.Expressions; public class Collection : IEnumerable { public void Add(int i, int j = 0) { } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public class C { public void M() { Expression<Func<Collection>> expr = () => new Collection { 1 }; // 1 } }"; CreateCompilation(text).VerifyDiagnostics( // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // () => new Collection { 1 }; // 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "1").WithLocation(18, 36)); } [Fact] public void CS0855ERR_ExpressionTreeContainsIndexedProperty() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface I Property P(index As Object) As Integer Property Q(Optional index As Object = Nothing) As Integer End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"using System; using System.Linq.Expressions; class C { static void M(I i) { Expression<Func<int>> e1; e1 = () => i.P[1]; e1 = () => i.get_P(2); // no error e1 = () => i.Q; e1 = () => i.Q[index:3]; Expression<Action> e2; e2 = () => i.P[4] = 0; e2 = () => i.set_P(5, 6); // no error } }"; var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[1]").WithLocation(8, 20), // (10,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q").WithLocation(10, 20), // (11,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q[index:3]").WithLocation(11, 20), // (13,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "i.P[4] = 0").WithLocation(13, 20), // (13,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[4]").WithLocation(13, 20)); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23004, "https://github.com/dotnet/roslyn/issues/23004")] public void CS0856ERR_IndexedPropertyRequiresParams01() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface I Property P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static void M(I i) { object o; o = i.P; // CS0856 (Dev11) o = i.Q; i.R = o; // CS0856 i.R[1] = o; // CS1501 o = i.S; // CS0856 (Dev11) i.S = o; // CS0856 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,9): error CS0856: Indexed property 'I.R' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "i.R").WithArguments("I.R").WithLocation(8, 9), // (9,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'I.R[int, int, int]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "i.R[1]").WithArguments("y", "I.R[int, int, int]").WithLocation(9, 9)); var tree = compilation2.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i.R[1]", node.ToString()); compilation2.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void CS0856ERR_IndexedPropertyRequiresParams02() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Protected ReadOnly Property P(Optional o As Object = Nothing) As Object Get Return Nothing End Get End Property Public ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static object F(A a) { return a.P; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,16): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "a.P").WithArguments("A.P").WithLocation(5, 16)); } [Fact] public void CS0857ERR_IndexedPropertyMustHaveAllOptionalParams() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> <CoClass(GetType(A))> Public Interface IA Property P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface Public Class A Implements IA Property P(x As Object, Optional y As Object = Nothing) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(x As Object, Optional y As Object = Nothing) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Implements IA.R Get Return Nothing End Get Set(value As Object) End Set End Property Property S(ParamArray args As Integer()) As Object Implements IA.S Get Return Nothing End Get Set(value As Object) End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes); var source2 = @"class B { static void M() { IA a; a = new IA() { P = null }; // CS0857 (Dev11) a = new IA() { Q = null }; a = new IA() { R = null }; // CS0857 a = new IA() { S = null }; // CS0857 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,24): error CS0857: Indexed property 'IA.R' must have all arguments optional Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, "R").WithArguments("IA.R").WithLocation(8, 24)); } [Fact] public void CS1059ERR_IncrementLvalueExpected01() { var text = @"enum E { A, B } class C { static void M() { ++E.A; // CS1059 E.A++; // CS1059 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 6, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 7, Column = 9 }); } [Fact] public void CS1059ERR_IncrementLvalueExpected02() { var text = @"class C { const int field = 0; static void M() { const int local = 0; ++local; local++; --field; field--; ++(local + 3); (local + 3)++; --2; 2--; dynamic d = null; (d + 1)++; --(d + 1); d++++; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (8,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (9,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (10,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (11,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (12,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (13,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (14,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (18,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (19,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d++")); } [Fact] public void CS1059ERR_IncrementLvalueExpected03() { var text = @" class C { void M() { ++this; // CS1059 this--; // CS1059 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // ++this; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this"), // (7,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // this--; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension01() { var text = @" public class TestClass1 { public void WriteSomething(string s) { System.Console.WriteLine(s); } } public class TestClass2 { public void DisplaySomething(string s) { System.Console.WriteLine(s); } } public class TestTheClasses { public static void Main() { TestClass1 tc1 = new TestClass1(); TestClass2 tc2 = new TestClass2(); if (tc1 == null | tc2 == null) {} tc1.DisplaySomething(""Hello""); // CS1061 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 25, Column = 13 } }); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension02() { var source = @"enum E { } class C { static void M(E e) { object o = e.value__; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,22): error CS1061: 'E' does not contain a definition for 'value__' and no extension method 'value__' accepting a first argument of type 'E' could be found (are you missing a using directive or an assembly reference?) // object o = e.value__; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "value__").WithArguments("E", "value__").WithLocation(6, 22)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension03() { CreateCompilation( @"class A { } class B { void M() { this.F(); this.P = this.Q; } static void M(A a) { a.F(); a.P = a.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("A", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("A", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("A", "Q"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("B", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("B", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("B", "Q")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension04() { CreateCompilation( @"using System.Collections.Generic; class C { static void M(List<object> list) { object o = list.Item; list.Item = o; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(6, 25), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(7, 14)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension05() { CreateCompilationWithMscorlib40AndSystemCore( @"using System.Linq; class Test { static void Main() { var q = 1.Select(z => z); } } ") .VerifyDiagnostics( // (7,17): error CS1061: 'int' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // var q = 1.Select(z => z); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Select").WithArguments("int", "Select").WithLocation(7, 19)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension06() { var source = @"interface I<T> { } static class C { static void M(object o) { o.M1(o, o); o.M2(o, o); } static void M1<T>(this I<T> o, object arg) { } static void M2<T>(this I<T> o, params object[] args) { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'M1' takes 2 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "2").WithLocation(6, 11), // (7,9): error CS1061: 'object' does not contain a definition for 'M2' and no extension method 'M2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M2").WithArguments("object", "M2").WithLocation(7, 11)); } [Fact] public void CS1113ERR_ValueTypeExtDelegate01() { var source = @"class C { public void M() { } } interface I { void M(); } enum E { } struct S { public void M() { } } static class SC { static void Test(C c, I i, E e, S s, double d) { System.Action cm = c.M; // OK -- instance method System.Action cm1 = c.M1; // OK -- extension method on ref type System.Action im = i.M; // OK -- instance method System.Action im2 = i.M2; // OK -- extension method on ref type System.Action em3 = e.M3; // BAD -- extension method on value type System.Action sm = s.M; // OK -- instance method System.Action sm4 = s.M4; // BAD -- extension method on value type System.Action dm5 = d.M5; // BAD -- extension method on value type } static void M1(this C c) { } static void M2(this I i) { } static void M3(this E e) { } static void M4(this S s) { } static void M5(this double d) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (24,29): error CS1113: Extension methods 'SC.M3(E)' defined on value type 'E' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "e.M3").WithArguments("SC.M3(E)", "E").WithLocation(24, 29), // (26,29): error CS1113: Extension methods 'SC.M4(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M4").WithArguments("SC.M4(S)", "S").WithLocation(26, 29), // (27,29): error CS1113: Extension methods 'SC.M5(double)' defined on value type 'double' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "d.M5").WithArguments("SC.M5(double)", "double").WithLocation(27, 29)); } [Fact] public void CS1113ERR_ValueTypeExtDelegate02() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { D d; d = i.M1; d = i.M2<int, object>; d = s.M1; d = s.M2<S, object>; d = t1.M1; d = t1.M2<T1, object>; d = t2.M1; d = t2.M2<T2, object>; d = t3.M1; d = t3.M2<T3, object>; d = t4.M1; d = t4.M2<T4, object>; d = t5.M1; d = t5.M2<T5, object>; } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (13,13): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(13, 13), // (14,13): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(14, 13), // (15,13): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(15, 13), // (16,13): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(16, 13), // (17,13): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(17, 13), // (18,13): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(18, 13), // (21,13): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(21, 13), // (22,13): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(22, 13), // (23,13): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(23, 13), // (24,13): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(24, 13)); } [WorkItem(528758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528758")] [Fact(Skip = "528758")] public void CS1113ERR_ValueTypeExtDelegate03() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { F(i.M1); F(i.M2<int, object>); F(s.M1); F(s.M2<S, object>); F(t1.M1); F(t1.M2<T1, object>); F(t2.M1); F(t2.M2<T2, object>); F(t3.M1); F(t3.M2<T3, object>); F(t4.M1); F(t4.M2<T4, object>); F(t5.M1); F(t5.M2<T5, object>); } static void F(D d) { } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilation(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (12,11): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(12, 11), // (13,11): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(13, 11), // (14,11): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(14, 11), // (15,11): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(15, 11), // (16,11): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(16, 11), // (17,11): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(17, 11), // (20,11): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(20, 11), // (21,11): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(21, 11), // (22,11): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(22, 11), // (23,11): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(23, 11)); } [Fact] public void CS1501ERR_BadArgCount() { var text = @" using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ExampleClass ec = new ExampleClass(); ec.ExampleMethod(10, 20); } } class ExampleClass { public void ExampleMethod() { Console.WriteLine(""Zero parameters""); } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgCount, Line = 11, Column = 16 } }); } [Fact] public void CS1502ERR_BadArgTypes() { var text = @" namespace x { public class a { public a(char i) { } public static void Main() { a aa = new a(2222); // CS1502 & CS1503 if (aa == null) {} } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 12, Column = 24 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 12, Column = 26 }}); } [Fact] public void CS1502ERR_BadArgTypes_ConstructorInitializer() { var text = @" namespace x { public class a { public a() : this(""string"") //CS1502, CS1503 { } public a(char i) { } } } "; CreateCompilation(text).VerifyDiagnostics( //// (6,22): error CS1502: The best overloaded method match for 'x.a.a(char)' has some invalid arguments //Diagnostic(ErrorCode.ERR_BadArgTypes, "this").WithArguments("x.a.a(char)"), //specifically omitted by roslyn // (6,27): error CS1503: Argument 1: cannot convert from 'string' to 'char' Diagnostic(ErrorCode.ERR_BadArgType, "\"string\"").WithArguments("1", "string", "char")); } [Fact] public void CS1503ERR_BadArgType01() { var source = @"namespace X { public class C { public C(int i, char c) { } static void M() { new C(1, 2); // CS1502 & CS1503 } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1503: Argument 2: cannot convert from 'int' to 'char' // new C(1, 2); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "2").WithArguments("2", "int", "char").WithLocation(10, 22)); } [Fact] public void CS1503ERR_BadArgType02() { var source = @"enum E1 { A, B, C } enum E2 { X, Y, Z } class C { static void F(int i) { } static void G(E1 e) { } static void M() { F(E1.A); // CS1502 & CS1503 F((E2)E1.B); // CS1502 & CS1503 F((int)E1.C); G(E2.X); // CS1502 & CS1503 G((E1)E2.Y); G((int)E2.Z); // CS1502 & CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from 'E1' to 'int' // F(E1.A); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E1.A").WithArguments("1", "E1", "int").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'E2' to 'int' // F((E2)E1.B); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(E2)E1.B").WithArguments("1", "E2", "int").WithLocation(10, 11), // (12,11): error CS1503: Argument 1: cannot convert from 'E2' to 'E1' // G(E2.X); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E2.X").WithArguments("1", "E2", "E1").WithLocation(12, 11), // (14,11): error CS1503: Argument 1: cannot convert from 'int' to 'E1' // G((int)E2.Z); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(int)E2.Z").WithArguments("1", "int", "E1").WithLocation(14, 11)); } [WorkItem(538939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538939")] [Fact] public void CS1503ERR_BadArgType03() { var source = @"class C { static void F(out int i) { i = 0; } static void M(long arg) { F(out arg); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // F(out arg); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "arg").WithArguments("1", "out long", "out int").WithLocation(9, 15)); } [Fact] public void CS1503ERR_BadArgType_MixedMethodsAndTypes() { var text = @" class A { public static void Goo(int x) { } } class B : A { public class Goo { } } class C : B { public static void Goo(string x) { } static void Main() { ((Goo))(1); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 8, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 22, IsWarning = true }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 16, Column = 5 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 16, Column = 13 } }); } [Fact] public void CS1510ERR_RefLvalueExpected_01() { var text = @"class C { void M(ref int i) { M(ref 2); // CS1510, can't pass a number as a ref parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_RefLvalueExpected, Line = 5, Column = 15 }); } [Fact] public void CS1510ERR_RefLvalueExpected_02() { var text = @"class C { void M() { var a = new System.Action<int>(ref x => x = 1); var b = new System.Action<int, int>(ref (x,y) => x = 1); var c = new System.Action<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_03() { var text = @"class C { void M() { var a = new System.Action<int>(out x => x = 1); var b = new System.Action<int, int>(out (x,y) => x = 1); var c = new System.Action<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_04() { var text = @"class C { void Goo<T>(ref System.Action<T> t) {} void Goo<T1,T2>(ref System.Action<T1,T2> t) {} void M() { Goo<int>(ref x => x = 1); Goo<int, int>(ref (x,y) => x = 1); Goo<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_05() { var text = @"class C { void Goo<T>(out System.Action<T> t) {t = null;} void Goo<T1,T2>(out System.Action<T1,T2> t) {t = null;} void M() { Goo<int>(out x => x = 1); Goo<int, int>(out (x,y) => x = 1); Goo<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_Strict() { var text = @"class C { void D(int i) {} void M() { System.Action<int> del = D; var a = new System.Action<int>(ref D); var b = new System.Action<int>(out D); var c = new System.Action<int>(ref del); var d = new System.Action<int>(out del); } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (8,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var a = new System.Action<int>(ref D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(8, 44), // (9,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var b = new System.Action<int>(out D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(9, 44), // (10,44): error CS0149: Method name expected // var c = new System.Action<int>(ref del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(10, 44), // (11,44): error CS0149: Method name expected // var d = new System.Action<int>(out del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(11, 44)); } [Fact] public void CS1511ERR_BaseInStaticMeth() { var text = @" public class A { public int j = 0; } class C : A { public void Method() { base.j = 3; // base allowed here } public static int StaticMethod() { base.j = 3; // CS1511 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInStaticMeth, Line = 16, Column = 7 } }); } [Fact] public void CS1511ERR_BaseInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = base.ToString(); } static object FLD = base.ToString(); static object PROP { get { return base.ToString(); } } static object METHOD() { return base.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS1511: Keyword 'base' is not available in a static method // static object FLD = base.ToString(); Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (6,28): error CS1511: Keyword 'base' is not available in a static method // static CLS() { var x = base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (8,39): error CS1511: Keyword 'base' is not available in a static method // static object PROP { get { return base.ToString(); } } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (9,37): error CS1511: Keyword 'base' is not available in a static method // static object METHOD() { return base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS1512ERR_BaseInBadContext() { var text = @" using System; class Base { } class CMyClass : Base { private String xx = base.ToString(); // CS1512 public static void Main() { CMyClass z = new CMyClass(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 8, Column = 25 } }); } [Fact] public void CS1512ERR_BaseInBadContext_AttributeArgument() { var text = @" using System; [assembly: A(P = base.ToString())] public class A : Attribute { public object P; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 4, Column = 18 } }); } [Fact] public void CS1520ERR_MemberNeedsType_02() { CreateCompilation( @"class Program { Main() {} Helper() {} \u0050rogram(int x) {} }") .VerifyDiagnostics( // (3,5): error CS1520: Method must have a return type // Main() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Main"), // (4,5): error CS1520: Method must have a return type // Helper() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Helper").WithLocation(4, 5) ); } [Fact] public void CS1525ERR_InvalidExprTerm() { CreateCompilation( @"public class MyClass { public static int Main() { bool b = string is string; return 1; } }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string")); } [WorkItem(543167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543167")] [Fact] public void CS1525ERR_InvalidExprTerm_1() { CreateCompilation( @"class D { public static void Main() { var s = 1?; } } ") .VerifyDiagnostics( // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,19): error CS1003: Syntax error, ':' expected // var s = 1?; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";"), // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,17): error CS0029: Cannot implicitly convert type 'int' to 'bool' // var s = 1?; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool") ); } [Fact] public void CS1525ERR_InvalidExprTerm_ConditionalOperator() { CreateCompilation( @"class Program { static void Main(string[] args) { int x = 1; int y = 1; System.Console.WriteLine(((x == y)) ?); // Invalid System.Console.WriteLine(((x == y)) ? (x++)); // Invalid System.Console.WriteLine(((x == y)) ? (x++) : (x++) : ((((y++))))); // Invalid System.Console.WriteLine(((x == y)) ? : :); // Invalid } } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":"), Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "("), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":")); } [WorkItem(528657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528657")] [Fact] public void CS0106ERR_BadMemberFlag() { CreateCompilation( @"new class MyClass { }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadMemberFlag, "MyClass").WithArguments("new")); } [Fact] public void CS1540ERR_BadProtectedAccess01() { var text = @" namespace CS1540 { class Program1 { static void Main() { Employee.PreparePayroll(); } } class Person { protected virtual void CalculatePay() { } } class Manager : Person { protected override void CalculatePay() { } } class Employee : Person { public static void PreparePayroll() { Employee emp1 = new Employee(); Person emp2 = new Manager(); Person emp3 = new Employee(); emp1.CalculatePay(); emp2.CalculatePay(); emp3.CalculatePay(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 35, Column = 18 }}); } [Fact] public void CS1540ERR_BadProtectedAccess02() { var text = @"class A { protected object F; protected void M() { } protected object P { get; set; } public object Q { get; protected set; } public object R { protected get; set; } public object S { private get; set; } } class B : A { void M(object o) { // base. base.M(); base.P = base.F; base.Q = null; M(base.R); M(base.S); // a. A a = new A(); a.M(); a.P = a.F; a.Q = null; M(a.R); M(a.S); // G(). G().M(); G().P = G().F; G().Q = null; M(G().R); M(G().S); // no qualifier M(); P = F; Q = null; M(R); M(S); // this. this.M(); this.P = this.F; this.Q = null; M(this.R); M(this.S); // ((A)this). ((A)this).M(); ((A)this).P = ((A)this).F; ((A)this).Q = null; M(((A)this).R); M(((A)this).S); } static A G() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (21,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(base.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "base.S").WithArguments("A.S"), // (24,11): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (25,11): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (25,17): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (26,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.Q").WithArguments("A.Q", "A", "B"), // (27,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(a.R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.R").WithArguments("A.R", "A", "B"), // (28,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(a.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "a.S").WithArguments("A.S"), // (30,13): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (31,13): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (31,21): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (32,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().Q").WithArguments("A.Q", "A", "B"), // (33,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(G().R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().R").WithArguments("A.R", "A", "B"), // (34,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(G().S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "G().S").WithArguments("A.S"), // (40,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "S").WithArguments("A.S"), // (46,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(this.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "this.S").WithArguments("A.S"), // (48,19): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (49,19): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (49,33): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (50,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).Q").WithArguments("A.Q", "A", "B"), // (51,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(((A)this).R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).R").WithArguments("A.R", "A", "B"), // (52,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(((A)this).S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "((A)this).S").WithArguments("A.S"), // (3,22): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // protected object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(540271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540271")] [Fact] public void CS0122ERR_BadAccessProtectedCtor() { // It is illegal to access any "protected" instance method with a "this" that is not of the // current class's type. Oddly enough, that includes constructors. It is legal to call // a protected ctor via ": base()" because then the "this" is of the derived type. But // in a derived class you cannot call "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540 whether the offending method is a regular // method or a ctor: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. That's what Roslyn does. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'Base.Base' is inaccessible due to its protection level var text = @"namespace CS0122 { public class Base { protected Base() {} } public class Derived : Base { void M() { Base b = new Base(); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("CS0122.Base.Base()")); } // CS1545ERR_BindToBogusProp2 --> Symbols\Source\EventTests.cs // CS1546ERR_BindToBogusProp1 --> Symbols\Source\PropertyTests.cs [WorkItem(528658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528658")] [Fact()] public void CS1560ERR_FileNameTooLong() { var text = @" #line 1 ""ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"" public class C { public void Main () { } } "; //EDMAURER no need to enforce a limit here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);//, //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FileNameTooLong, Line = 1, Column = 25 } }); } [Fact] public void CS1579ERR_ForEachMissingMember() { var text = @" using System; public class MyCollection { int[] items; public MyCollection() { items = new int[5] { 12, 44, 33, 2, 50 }; } MyEnumerator GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public bool MoveNext() { nIndex++; return (nIndex < collection.items.GetLength(0)); } public int Current { get { return (collection.items[nIndex]); } } } public static void Main() { MyCollection col = new MyCollection(); Console.WriteLine(""Values in the collection are:""); foreach (int i in col) // CS1579 { Console.WriteLine(i); } } }"; CreateCompilation(text).VerifyDiagnostics( // (45,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method. // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "col").WithArguments("MyCollection", "collection", "MyCollection.GetEnumerator()"), // (45,27): error CS1579: foreach statement cannot operate on variables of type 'MyCollection' because 'MyCollection' does not contain a public definition for 'GetEnumerator' // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.ERR_ForEachMissingMember, "col").WithArguments("MyCollection", "GetEnumerator")); } [Fact] public void CS1579ERR_ForEachMissingMember02() { var text = @" public class Test { public static void Main(string[] args) { foreach (int x in F(1)) { } } static void F(int x) { } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ForEachMissingMember, "F(1)").WithArguments("void", "GetEnumerator")); } [Fact] public void CS1593ERR_BadDelArgCount() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(8, 9); // CS1593 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgCount, Line = 21, Column = 9 } }); } [Fact] public void CS1593ERR_BadDelArgCount_02() { var text = @" delegate void MyDelegate1(int x, float y); class Program { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1); md1 -= mc.DelegatedMethod; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'MyDelegate1' // md1(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "md1").WithArguments("y", "MyDelegate1").WithLocation(11, 9)); } [Fact] public void CS1593ERR_BadDelArgCount_03() { var text = @" using System; class Program { static void Main() { new Action<int>(Console.WriteLine)(1, 1); } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadDelArgCount, "new Action<int>(Console.WriteLine)").WithArguments("System.Action<int>", "2")); } [Fact()] public void CS1594ERR_BadDelArgTypes() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(""8""); // CS1594 } } "; //EDMAURER Giving errors for the individual argument problems is better than generic "delegate 'blah' has some invalid arguments" DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 21, Column = 15 } }); //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgTypes, Line = 21, Column = 9 } }); } // TODO: change this to CS0051 in Roslyn? [Fact] public void CS1604ERR_AssgReadonlyLocal() { var text = @" class C { void M() { this = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS1604: Cannot assign to 'this' because it is read-only Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1605ERR_RefReadonlyLocal() { var text = @" class C { void Test() { Ref(ref this); //CS1605 Out(out this); //CS1605 } static void Ref(ref C c) { } static void Out(out C c) { c = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this"), // (7,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1612ERR_ReturnNotLValue01() { var text = @" public struct MyStruct { public int Width; } public class ListView { MyStruct ms; public MyStruct Size { get { return ms; } set { ms = value; } } } public class MyClass { public MyClass() { ListView lvi; lvi = new ListView(); lvi.Size.Width = 5; // CS1612 } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnNotLValue, Line = 23, Column = 9 } }); } /// <summary> /// Breaking change from Dev10. CS1612 is now reported for all value /// types, not just struct types. Specifically, CS1612 is now reported /// for type parameters constrained to "struct". (See also CS0131.) /// </summary> [WorkItem(528821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528821")] [Fact] public void CS1612ERR_ReturnNotLValue02() { var source = @"interface I { object P { get; set; } } struct S : I { public object P { get; set; } } class C<T, U, V> where T : struct, I where U : class, I where V : I { S F1 { get; set; } T F2 { get; set; } U F3 { get; set; } V F4 { get; set; } void M() { F1.P = null; F2.P = null; F3.P = null; F4.P = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F1' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F1").WithArguments("C<T, U, V>.F1").WithLocation(20, 9), // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F2' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F2").WithArguments("C<T, U, V>.F2").WithLocation(21, 9)); } [Fact] public void CS1615ERR_BadArgExtraRef() { var text = @" class C { public void f(int i) {} public static void Main() { int i = 1; f(ref i); // CS1615 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 7 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgExtraRef, Line = 8, Column = 13 } }); } [Fact()] public void CS1618ERR_DelegateOnConditional() { var text = @" using System.Diagnostics; delegate void del(); class MakeAnError { public static void Main() { del d = new del(ConditionalMethod); // CS1618 } [Conditional(""DEBUG"")] public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // del d = new del(ConditionalMethod); // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(10, 25)); } [Fact()] public void CS1618ERR_DelegateOnConditional_02() { var text = @" using System; using System.Diagnostics; delegate void del(); class MakeAnError { class Goo: Attribute { public Goo(object o) {} } [Conditional(""DEBUG"")] [Goo(new del(ConditionalMethod))] // CS1618 public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,18): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // [Goo(new del(ConditionalMethod))] // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(15, 18)); } [Fact] public void CS1620ERR_BadArgRef() { var text = @" class C { void f(ref int i) { } public static void Main() { int x = 1; f(out x); // CS1620 - f takes a ref parameter, not an out parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 9 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgRef, Line = 8, Column = 15 } }); } [Fact] public void CS1621ERR_YieldInAnonMeth() { var text = @" using System.Collections; delegate object MyDelegate(); class C : IEnumerable { public IEnumerator GetEnumerator() { MyDelegate d = delegate { yield return this; // CS1621 return this; }; d(); } public static void Main() { } } "; var comp = CreateCompilation(text); var expected = new DiagnosticDescription[] { // (12,13): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield return this; // CS1621 Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // (8,24): error CS0161: 'C.GetEnumerator()': not all code paths return a value // public IEnumerator GetEnumerator() Diagnostic(ErrorCode.ERR_ReturnExpected, "GetEnumerator").WithArguments("C.GetEnumerator()") }; comp.VerifyDiagnostics(expected); comp.VerifyEmitDiagnostics(expected); } [Fact] public void CS1622ERR_ReturnInIterator() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { return (IEnumerator) this; // CS1622 yield return this; // OK } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,7): error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration. // return (IEnumerator) this; // CS1622 Diagnostic(ErrorCode.ERR_ReturnInIterator, "return"), // (9,7): warning CS0162: Unreachable code detected // yield return this; // OK Diagnostic(ErrorCode.WRN_UnreachableCode, "yield") ); } [Fact] public void CS1623ERR_BadIteratorArgType() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } public IEnumerator GetEnumerator(ref int i) // CS1623 { yield return i; } public IEnumerator GetEnumerator(out float f) // CS1623 { f = 0.0F; yield return f; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,46): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(ref int i) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "i"), // (16,48): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(out float f) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "f") ); } [Fact] public void CS1624ERR_BadIteratorReturn() { var text = @" class C { public int Iterator { get // CS1624 { yield return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIteratorReturn, Line = 6, Column = 9 } }); } [Fact] public void CS1625ERR_BadYieldInFinally() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { } finally { yield return this; // CS1625 } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,9): error CS1625: Cannot yield in the body of a finally clause // yield return this; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield") ); } [Fact] public void CS1626ERR_BadYieldInTryOfCatch() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { yield return this; // CS1626 } catch { } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,10): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return this; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield") ); } [Fact] public void CS1628ERR_AnonDelegateCantUse() { var text = @" delegate int MyDelegate(); class C { public static void F(ref int i) { MyDelegate d = delegate { return i; }; // CS1628 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonDelegateCantUse, Line = 8, Column = 42 } }); } [Fact] public void CS1629ERR_IllegalInnerUnsafe() { var text = @" using System.Collections.Generic; class C { IEnumerator<int> IteratorMeth() { int i; unsafe // CS1629 { int *p = &i; yield return *p; } } unsafe IEnumerator<int> IteratorMeth2() { // CS1629 yield break; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,7): error CS1629: Unsafe code may not appear in iterators // unsafe // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"), // (9,10): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int *"), // (9,19): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&i"), // (10,24): error CS1629: Unsafe code may not appear in iterators // yield return *p; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "p"), // (14,29): error CS1629: Unsafe code may not appear in iterators // unsafe IEnumerator<int> IteratorMeth2() { // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "IteratorMeth2") ); } [Fact] public void CS1631ERR_BadYieldInCatch() { var text = @" using System; using System.Collections; public class C : IEnumerable { public IEnumerator GetEnumerator() { try { } catch(Exception e) { yield return this; // CS1631 } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS1631: Cannot yield a value in the body of a catch clause // yield return this; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (12,23): warning CS0168: The variable 'e' is declared but never used // catch(Exception e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e") ); } [Fact] public void CS1632ERR_BadDelegateLeave() { var text = @" delegate void MyDelegate(); class MyClass { public void Test() { for (int i = 0 ; i < 5 ; i++) { MyDelegate d = delegate { break; // CS1632 }; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,13): error CS1632: Control cannot leave the body of an anonymous method or lambda expression // break; // CS1632 Diagnostic(ErrorCode.ERR_BadDelegateLeave, "break") ); } [Fact] public void CS1636ERR_VarargsIterator() { var text = @"using System.Collections; public class Test { IEnumerable Goo(__arglist) { yield return 1; } static int Main(string[] args) { return 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,17): error CS1636: __arglist is not allowed in the parameter list of iterators // IEnumerable Goo(__arglist) Diagnostic(ErrorCode.ERR_VarargsIterator, "Goo")); } [Fact] public void CS1637ERR_UnsafeIteratorArgType() { var text = @" using System.Collections; public unsafe class C { public IEnumerator Iterator1(int* p) // CS1637 { yield return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,39): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p")); } [Fact()] public void CS1639ERR_BadCoClassSig() { // BREAKING CHANGE: Dev10 allows this test to compile, even though the output assembly is not verifiable and generates a runtime exception: // BREAKING CHANGE: We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""00020810-0000-0000-C000-000000000046"")] [CoClass(typeof(GenericClass<>))] public interface InterfaceType {} public class GenericClass<T>: InterfaceType {} public class Program { public static void Main() { var i = new InterfaceType(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadCoClassSig, Line = 12, Column = 41 } } ); } [Fact()] public void CS1640ERR_MultipleIEnumOfT() { var text = @" using System.Collections; using System.Collections.Generic; public class C : IEnumerable, IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield break; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)((IEnumerable<string>)this).GetEnumerator(); } } public class Test { public static int Main() { foreach (int i in new C()) { } // CS1640 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MultipleIEnumOfT, Line = 27, Column = 27 } }); } [WorkItem(7389, "DevDiv_Projects/Roslyn")] [Fact] public void CS1640ERR_MultipleIEnumOfT02() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { } } public class C<T> where T : IEnumerable<int>, IEnumerable<string> { public static void TestForeach(T t) { foreach (int i in t) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t").WithArguments("T", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t").WithArguments("T", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS1643ERR_AnonymousReturnExpected() { var text = @" delegate int MyDelegate(); class C { static void Main() { MyDelegate d = delegate { // CS1643 int i = 0; if (i == 0) return 1; }; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS1643: Not all code paths return a value in anonymous method of type 'MyDelegate' // MyDelegate d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "MyDelegate").WithLocation(8, 24) ); } [Fact] public void CS1643ERR_AnonymousReturnExpected_Foreach() { var text = @" using System; public class Test { public static void Main(string[] args) { string[] arr = null; Func<int> f = () => { foreach (var x in arr) return x; }; } } "; CreateCompilation(text). VerifyDiagnostics( // (8,61): error CS0029: Cannot implicitly convert type 'string' to 'int' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("string", "int").WithLocation(8, 61), // (8,61): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x").WithArguments("lambda expression").WithLocation(8, 61), // (8,26): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(8, 26) ); } [Fact] public void CS1648ERR_AssgReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void Main() { Outer outer = new Outer(); outer.inner.i = 1; // CS1648 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonly2, Line = 17, Column = 7 } }); } [Fact] public void CS1649ERR_RefReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { Outer outer = new Outer(); f(ref outer.inner.i); // CS1649 } } "; CreateCompilation(text).VerifyDiagnostics( // (21,15): error CS1649: Members of readonly field 'Outer.inner' cannot be used as a ref or out value (except in a constructor) // f(ref outer.inner.i); // CS1649 Diagnostic(ErrorCode.ERR_RefReadonly2, "outer.inner.i").WithArguments("Outer.inner").WithLocation(21, 15) ); } [Fact] public void CS1650ERR_AssgReadonlyStatic2() { string text = @"public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void Main() { Outer.inner.i = 1; // CS1650 } } "; CreateCompilation(text).VerifyDiagnostics( // (15,9): error CS1650: Fields of static readonly field 'Outer.inner' cannot be assigned to (except in a static constructor or a variable initializer) Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1651ERR_RefReadonlyStatic2() { var text = @" public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { f(ref Outer.inner.i); // CS1651 } } "; CreateCompilation(text).VerifyDiagnostics( // (20,15): error CS1651: Fields of static readonly field 'Outer.inner' cannot be passed ref or out (except in a static constructor) Diagnostic(ErrorCode.ERR_RefReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1654ERR_AssgReadonlyLocal2Cause() { var text = @" using System.Collections.Generic; namespace CS1654 { struct Book { public string Title; public string Author; public double Price; public Book(string t, string a, double p) { Title = t; Author = a; Price = p; } } class Program { List<Book> list; static void Main(string[] args) { Program prog = new Program(); prog.list = new List<Book>(); foreach (Book b in prog.list) { b.Price += 9.95; // CS1654 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (29,17): error CS1654: Cannot modify members of 'b' because it is a 'foreach iteration variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocal2Cause, "b.Price").WithArguments("b", "foreach iteration variable")); } [Fact] public void CS1655ERR_RefReadonlyLocal2Cause() { var text = @" struct S { public int i; } class CMain { static void f(ref int iref) { } public static void Main() { S[] sa = new S[10]; foreach(S s in sa) { CMain.f(ref s.i); // CS1655 } } } "; CreateCompilation(text).VerifyDiagnostics( // (18,21): error CS1655: Cannot pass fields of 's' as a ref or out argument because it is a 'foreach iteration variable' // CMain.f(ref s.i); // CS1655 Diagnostic(ErrorCode.ERR_RefReadonlyLocal2Cause, "s.i").WithArguments("s", "foreach iteration variable") ); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause01() { var text = @" using System; class C : IDisposable { public void Dispose() { } } class CMain { unsafe public static void Main() { using (C c = new C()) { c = new C(); // CS1656 } int[] ary = new int[] { 1, 2, 3, 4 }; fixed (int* p = ary) { p = null; // CS1656 } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,13): error CS1656: Cannot assign to 'c' because it is a 'using variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "c").WithArguments("c", "using variable").WithLocation(15, 13), // (19,13): error CS1656: Cannot assign to 'p' because it is a 'fixed variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "p").WithArguments("p", "fixed variable").WithLocation(21, 13)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause02() { var text = @"class C { static void M() { M = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS1656: Cannot assign to 'M' because it is a 'method group' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "M").WithArguments("M", "method group").WithLocation(5, 9)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause_NestedForeach() { var text = @" public class Test { static public void Main(string[] args) { string S = ""ABC""; string T = ""XYZ""; foreach (char x in S) { foreach (char y in T) { x = 'M'; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable")); } [Fact] public void CS1657ERR_RefReadonlyLocalCause() { var text = @" class C { static void F(ref string s) { } static void Main(string[] args) { foreach (var a in args) { F(ref a); //CS1657 } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,19): error CS1657: Cannot use 'a' as a ref or out value because it is a 'foreach iteration variable' // F(ref a); //CS1657 Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "a").WithArguments("a", "foreach iteration variable").WithLocation(12, 19) ); } [Fact] public void CS1660ERR_AnonMethToNonDel() { var text = @" delegate int MyDelegate(); class C { static void Main() { int i = delegate { return 1; }; // CS1660 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethToNonDel, Line = 6, Column = 14 } }); } [Fact] public void CS1661ERR_CantConvAnonMethParams() { var text = @" delegate void MyDelegate(int i); class C { public static void Main() { MyDelegate d = delegate(string s) { }; // CS1661 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 8, Column = 40 } }); } [Fact] public void CS1662ERR_CantConvAnonMethReturns() { var text = @" delegate int MyDelegate(int i); class C { delegate double D(); public static void Main() { MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 D dd = () => { return ""Who knows the real sword of Gryffindor?""; }; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,49): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(9, 49), // (9,49): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("anonymous method").WithLocation(9, 49), // (10,31): error CS0029: Cannot implicitly convert type 'string' to 'double' // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who knows the real sword of Gryffindor?""").WithArguments("string", "double").WithLocation(10, 31), // (10,31): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""Who knows the real sword of Gryffindor?""").WithArguments("lambda expression").WithLocation(10, 31) ); } [Fact] public void CS1666ERR_FixedBufferNotFixedErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (13,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(13, 30), // (15,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(15, 30), // (22,17): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(22, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotUnsafeErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (13,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "inst.field.buffer").WithLocation(13, 30), // (20,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_UnsafeNeeded, "field.buffer").WithLocation(20, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotFixed() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; var c = CompileAndVerify(text, expectedOutput: "7788", verify: Verification.Fails, options: TestOptions.UnsafeReleaseExe); c.VerifyIL("Test.example1()", @" { // Code size 22 (0x16) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: ldc.i4.7 IL_0011: dup IL_0012: stloc.0 IL_0013: stind.i4 IL_0014: ldloc.0 IL_0015: ret } "); c.VerifyIL("Test.example2()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (pinned int& V_0, int V_1) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: conv.u IL_0013: ldc.i4.8 IL_0014: dup IL_0015: stloc.1 IL_0016: stind.i4 IL_0017: ldloc.1 IL_0018: ret } "); } [Fact] public void CS1669ERR_IllegalVarArgs01() { var source = @"class C { delegate void D(__arglist); // CS1669 static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS1669: __arglist is not valid in this context // delegate void D(__arglist); // CS1669 Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [Fact] public void CS1669ERR_IllegalVarArgs02() { var source = @"class C { object this[object index, __arglist] { get { return null; } } public static C operator +(C c1, __arglist) { return c1; } public static implicit operator int(__arglist) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,31): error CS1669: __arglist is not valid in this context // object this[object index, __arglist] Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (7,38): error CS1669: __arglist is not valid in this context // public static C operator +(C c1, __arglist) { return c1; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (8,41): error CS1669: __arglist is not valid in this context // public static implicit operator int(__arglist) { return 0; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [WorkItem(863433, "DevDiv/Personal")] [Fact] public void CS1670ERR_IllegalParams() { // TODO: extra 1670 (not check for now) var test = @" delegate int MyDelegate(params int[] paramsList); class Test { public static int Main() { MyDelegate d = delegate(params int[] paramsList) // CS1670 { return paramsList[0]; }; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IllegalParams, Line = 7, Column = 33 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth01() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = this.member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth02() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1674ERR_NoConvToIDisp() { var text = @" class C { public static void Main() { using (int a = 0) // CS1674 using (a); //CS1674 } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): warning CS0642: Possible mistaken empty statement Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (6,16): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int a = 0").WithArguments("int"), // (7,20): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "a").WithArguments("int")); } [Fact] public void CS1676ERR_BadParamRef() { var text = @" delegate void E(ref int i); class Errors { static void Main() { E e = delegate(out int i) { }; // CS1676 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,13): error CS1661: Cannot convert anonymous method to delegate type 'E' because the parameter types do not match the delegate parameter types // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "E"), // (7,22): error CS1676: Parameter 1 must be declared with the 'ref' keyword // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_BadParamRef, "i").WithArguments("1", "ref"), // (7,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1677ERR_BadParamExtraRef() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(out int i) { }; // CS1677 D d = delegate(ref int j) { }; // CS1677 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "D"), // (7,24): error CS1677: Parameter 1 should not be declared with the 'out' keyword // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "i").WithArguments("1", "out"), // (8,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(ref int j) { }").WithArguments("anonymous method", "D"), // (8,24): error CS1677: Parameter 1 should not be declared with the 'ref' keyword // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "j").WithArguments("1", "ref"), // (8,11): error CS0128: A local variable named 'd' is already defined in this scope // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_LocalDuplicate, "d").WithArguments("d"), // (7,15): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1678ERR_BadParamType() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(string s) { }; // CS1678 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 7, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 7, Column = 31 } }); } [Fact] public void CS1681ERR_GlobalExternAlias() { var text = @" extern alias global; class myClass { static int Main() { //global::otherClass oc = new global::otherClass(); return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (2,14): error CS1681: You cannot redefine the global extern alias // extern alias global; Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"), // (2,14): error CS0430: The extern alias 'global' was not specified in a /reference option // extern alias global; Diagnostic(ErrorCode.ERR_BadExternAlias, "global").WithArguments("global"), // (2,1): info CS8020: Unused extern alias. // extern alias global; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias global;") ); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted() { var text = @" class MyClass { public unsafe delegate int* MyDelegate(); public unsafe int* Test() { int j = 0; MyDelegate d = delegate { return &j; }; // CS1686 return &j; // CS1686 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,42): error CS1686: Local 'j' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // MyDelegate d = delegate { return &j; }; // CS1686 Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&j").WithArguments("j")); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted02() { var text = @"using System; unsafe struct S { public fixed int buffer[1]; public int i; } unsafe class Test { private void example1() { S data = new S(); data.i = data.i + 1; Func<S> lambda = () => data; fixed (int* p = data.buffer) // fail due to receiver being a local { } int *q = data.buffer; // fail due to lambda capture } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* p = data.buffer) // fail due to receiver being a local Diagnostic(ErrorCode.ERR_FixedNotNeeded, "data.buffer"), // (19,18): error CS1686: Local 'data' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int *q = data.buffer; // fail due to lambda capture Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "data.buffer").WithArguments("data") ); } [WorkItem(580537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580537")] [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted03() { var text = @"unsafe public struct Test { private delegate int D(); public fixed int i[1]; public void example() { Test t = this; t.i[0] = 5; D d = delegate { var x = t; return 0; }; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,9): error CS1686: Local 't' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // t.i[0] = 5; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t") ); } [Fact] public void CS1688ERR_CantConvAnonMethNoParams() { var text = @" using System; delegate void OutParam(out int i); class ErrorCS1676 { static void Main() { OutParam o; o = delegate // CS1688 { Console.WriteLine(""); }; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,31): error CS1010: Newline in constant // Console.WriteLine("); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(11, 31), // (11,34): error CS1026: ) expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(11, 34), // (11,34): error CS1002: ; expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 34), // (9,13): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'OutParam' because it has one or more out parameters // o = delegate // CS1688 Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, @"delegate // CS1688 { Console.WriteLine(""); }").WithArguments("OutParam").WithLocation(9, 13) ); } [Fact] public void CS1708ERR_FixedNeedsLvalue() { var text = @" unsafe public struct S { public fixed char name[10]; } public unsafe class C { public S UnsafeMethod() { S myS = new S(); return myS; } static void Main() { C myC = new C(); myC.UnsafeMethod().name[3] = 'a'; // CS1708 C._s1.name[3] = 'a'; // CS1648 myC._s2.name[3] = 'a'; // CS1648 } static readonly S _s1; public readonly S _s2; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (18,9): error CS1708: Fixed size buffers can only be accessed through locals or fields // myC.UnsafeMethod().name[3] = 'a'; // CS1708 Diagnostic(ErrorCode.ERR_FixedNeedsLvalue, "myC.UnsafeMethod().name").WithLocation(18, 9), // (19,9): error CS1650: Fields of static readonly field 'C._s1' cannot be assigned to (except in a static constructor or a variable initializer) // C._s1.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "C._s1.name[3]").WithArguments("C._s1").WithLocation(19, 9), // (20,9): error CS1648: Members of readonly field 'C._s2' cannot be modified (except in a constructor, an init-only member or a variable initializer) // myC._s2.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonly2, "myC._s2.name[3]").WithArguments("C._s2").WithLocation(20, 9) ); } [Fact, WorkItem(543995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543995"), WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")] public void CS1728ERR_DelegateOnNullable() { var text = @" using System; class Test { static void Main() { int? x = null; Func<string> f1 = x.ToString; // no error Func<int> f2 = x.GetHashCode; // no error Func<object, bool> f3 = x.Equals; // no error Func<Type> f4 = x.GetType; // no error Func<int> x1 = x.GetValueOrDefault; // 1728 Func<int, int> x2 = x.GetValueOrDefault; // 1728 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,24): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault()' because it is a member of 'System.Nullable<T>' // Func<int> x1 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()"), // (15,29): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault(int)' because it is a member of 'System.Nullable<T>' // Func<int, int> x2 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault(int)") ); } [Fact, WorkItem(999399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399")] public void CS1729ERR_BadCtorArgCount() { var text = @" class Test { static int Main() { double d = new double(4.5); // was CS0143 (Dev10) Test test1 = new Test(2); // CS1729 Test test2 = new Test(); Parent exampleParent1 = new Parent(10); // CS1729 Parent exampleParent2 = new Parent(10, 1); if (test1 == test2 & exampleParent1 == exampleParent2) {} return 1; } } public class Parent { public Parent(int i, int j) { } } public class Child : Parent { } // CS1729 public class Child2 : Parent { public Child2(int k) : base(k, 0) { } }"; var compilation = CreateCompilation(text); DiagnosticDescription[] expected = { // (21,14): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Parent.Parent(int, int)' // public class Child : Parent { } // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Child").WithArguments("i", "Parent.Parent(int, int)").WithLocation(21, 14), // (6,24): error CS1729: 'double' does not contain a constructor that takes 1 arguments // double d = new double(4.5); // was CS0143 (Dev10) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "double").WithArguments("double", "1").WithLocation(6, 24), // (7,26): error CS1729: 'Test' does not contain a constructor that takes 1 arguments // Test test1 = new Test(2); // CS1729 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("Test", "1").WithLocation(7, 26), // (9,37): error CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'Parent.Parent(int, int)' // Parent exampleParent1 = new Parent(10); // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Parent").WithArguments("j", "Parent.Parent(int, int)").WithLocation(9, 37) }; compilation.VerifyDiagnostics(expected); compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single(), filterSpanWithinTree: null, includeEarlierStages: true).Verify(expected); } [WorkItem(539631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539631")] [Fact] public void CS1729ERR_BadCtorArgCount02() { var text = @" class MyClass { int intI = 1; MyClass() { intI = 2; } //this constructor initializer MyClass(int intJ) : this(3, 4) // CS1729 { intI = intI * intJ; } } class MyBase { public int intI = 1; protected MyBase() { intI = 2; } protected MyBase(int intJ) { intI = intJ; } } class MyDerived : MyBase { MyDerived() : base(3, 4) // CS1729 { intI = intI * 2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 32, Column = 19 }); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @" class C { public void Goo(string s = null, int x) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueBeforeRequiredValue, Line = 4, Column = 43 } } //sic: error on close paren ); } [WorkItem(539007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539007")] [Fact] public void DevDiv4792_OptionalBeforeParams() { var text = @" class C { public void Goo(string s = null, params int[] ints) { } } "; //no errors var comp = CreateCompilation(text); Assert.False(comp.GetDiagnostics().Any()); } [WorkItem(527351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527351")] [Fact] public void CS1738ERR_NamedArgumentSpecificationBeforeFixedArgument() { var text = @" public class C { public static int Main() { Test(age: 5,""""); return 0; } public static void Test(int age, string Name) { } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test(age: 5,""); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, @"""""").WithArguments("7.2").WithLocation(6, 21) ); } [Fact] public void CS1739ERR_BadNamedArgument() { var text = @" public class C { public static int Main() { Test(5,Nam:null); return 0; } public static void Test(int age , string Name) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact, WorkItem(866112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866112")] public void CS1739ERR_BadNamedArgument_1() { var text = @" public class C { public static void Main() { Test(1, 2, Name:3); } public static void Test(params int [] array) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact] public void CS1740ERR_DuplicateNamedArgument() { var text = @" public class C { public static int Main() { Test(age: 5, Name: ""5"", Name: """"); return 0; } public static void Test(int age, string Name) { } }"; var compilation = CSharpTestBase.CreateCompilation(text); compilation.VerifyDiagnostics( // (6,33): error CS1740: Named argument 'Name' cannot be specified multiple times // Test(age: 5, Name: "5", Name: ""); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "Name").WithArguments("Name").WithLocation(6, 33)); } [Fact] public void CS1742ERR_NamedArgumentForArray() { var text = @" public class B { static int Main() { int[] arr = { }; int s = arr[arr: 1]; s = s + 1; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1742, Line = 7, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional() { var text = @" public class C { public static int Main() { Test(5, age: 3); return 0; } public static void Test(int age , string Name) { } }"; // CS1744: Named argument 'q' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 21 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional2() { // Unfortunately we allow "void M(params int[] x)" to be called in the expanded // form as "M(x : 123);". However, we still do not allow "M(123, x:456);". var text = @" public class C { public static void Main() { Test(5, x: 3); } public static void Test(params int[] x) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional3() { var text = @" public class C { public static void Main() { Test(5, x : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional4() { var text = @" public class C { public static void Main() { Test(5, 6, 7, 8, 9, 10, z : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'z' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 33 } }); } [Fact] public void CS1746ERR_BadNamedArgumentForDelegateInvoke() { var text = @" public class C { delegate int MyDg(int age); public static int Main() { MyDg dg = new MyDg(Test); int S = dg(Ne: 3); return 0; } public static int Test(int age) { return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1746, Line = 8, Column = 24 } }); } // [Fact()] // public void CS1752ERR_FixedNeedsLvalue() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FixedNeedsLvalue, Line = 20, Column = 9 } } // ); // } // CS1912 --> ObjectAndCollectionInitializerTests.cs // CS1913 --> ObjectAndCollectionInitializerTests.cs // CS1914 --> ObjectAndCollectionInitializerTests.cs // CS1917 --> ObjectAndCollectionInitializerTests.cs // CS1918 --> ObjectAndCollectionInitializerTests.cs // CS1920 --> ObjectAndCollectionInitializerTests.cs // CS1921 --> ObjectAndCollectionInitializerTests.cs // CS1922 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1919ERR_UnsafeTypeInObjectCreation() { var text = @" unsafe public class C { public static int Main() { var col1 = new int*(); // CS1919 var col2 = new char*(); // CS1919 return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS1919: Unsafe type 'int*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new int*()").WithArguments("int*"), // (7,20): error CS1919: Unsafe type 'char*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new char*()").WithArguments("char*")); } [Fact] public void CS1928ERR_BadExtensionArgTypes() { var text = @"class C { static void M(float f) { f.F(); } } static class S { internal static void F(this double d) { } }"; var compilation = CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }); // Previously ERR_BadExtensionArgTypes. compilation.VerifyDiagnostics( // (5,9): error CS1929: 'float' does not contain a definition for 'F' and the best extension method overload 'S.F(double)' requires a receiver of type 'double' // f.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "f").WithArguments("float", "F", "S.F(double)", "double").WithLocation(5, 9)); } [Fact] public void CS1929ERR_BadInstanceArgType() { var source = @"class A { } class B : A { static void M(A a) { a.E(); } } static class S { internal static void E(this B b) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }); compilation.VerifyDiagnostics( // (6,9): error CS1929: 'A' does not contain a definition for 'E' and the best extension method overload 'S.E(B)' requires a receiver of type 'B' // a.E(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "E", "S.E(B)", "B").WithLocation(6, 9) ); } [Fact] public void CS1930ERR_QueryDuplicateRangeVariable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Program { static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; var query = from num in nums let num = 3 // CS1930 select num; } } ").VerifyDiagnostics( // (10,25): error CS1930: The range variable 'num' has already been declared Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "num").WithArguments("num")); } [Fact] public void CS1931ERR_QueryRangeVariableOverrides01() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int x = 1; var y = from x in Enumerable.Range(1, 100) // CS1931 select x + 1; } } ").VerifyDiagnostics( // (9,22): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var y = from x in Enumerable.Range(1, 100) // CS1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x"), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = null select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign <null> to a range variable // let k = null Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = null").WithArguments("<null>") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = ()=>3 select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign lambda expression to a range variable // let k = ()=>3 Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = ()=>3").WithArguments("lambda expression") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue03() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = Main select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign method group to a range variable // let k = Main Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = Main").WithArguments("method group") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue04() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = M() select i; } static void M() {} } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign void to a range variable // let k = M() Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = M()").WithArguments("void") ); } [WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")] [Fact()] public void CS1933ERR_QueryNotAllowed() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; class P { const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 static int Main() { return 1; } } ").VerifyDiagnostics( // EDMAURER now giving the more generic message CS0133 // (7,27): error CS1933: Expression cannot contain query expressions // from //Diagnostic(ErrorCode.ERR_QueryNotAllowed, "from").WithArguments()); // (7,27): error CS0133: The expression being assigned to 'P.e' must be constant // const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 Diagnostic(ErrorCode.ERR_NotConstantExpression, "from x in new int[] { 1, 2, 3 } select x").WithArguments("P.e") ); } [Fact] public void CS1934ERR_QueryNoProviderCastable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; static class Test { public static void Main() { var list = new ArrayList(); var q = from x in list // CS1934 select x + 1; } } ").VerifyDiagnostics( // (9,27): error CS1934: Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'x'. // list Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, "list").WithArguments("System.Collections.ArrayList", "Select", "x")); } [Fact] public void CS1935ERR_QueryNoProviderStandard() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections.Generic; class Test { static int Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; IEnumerable<int> e = from n in nums where n > 3 select n; return 0; } } ").VerifyDiagnostics( // (8,40): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Where' not found. Are you missing required assembly references or a using directive for 'System.Linq'? // nums Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "nums").WithArguments("int[]", "Where")); } [Fact] public void CS1936ERR_QueryNoProvider() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { object obj = null; IEnumerable e = from x in obj // CS1936 select x; return 0; } } ").VerifyDiagnostics( // (10,35): error CS1936: Could not find an implementation of the query pattern for source type 'object'. 'Select' not found. // obj Diagnostic(ErrorCode.ERR_QueryNoProvider, "obj").WithArguments("object", "Select")); } [Fact] public void CS1936ERR_QueryNoProvider01() { var program = @" class X { internal X Cast<T>() { return this; } } class Program { static void Main() { var xx = new X(); var q3 = from int x in xx select x; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,32): error CS1936: Could not find an implementation of the query pattern for source type 'X'. 'Select' not found. // var q3 = from int x in xx select x; Diagnostic(ErrorCode.ERR_QueryNoProvider, "xx").WithArguments("X", "Select") ); } [Fact] public void CS1937ERR_QueryOuterKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on b equals 5 // CS1937 select a + b; } } ").VerifyDiagnostics( // (11,42): error CS1937: The name 'b' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on b equals 5 // CS1937 Diagnostic(ErrorCode.ERR_QueryOuterKey, "b").WithArguments("b") ); } [Fact] public void CS1938ERR_QueryInnerKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on 5 equals a // CS1938 select a + b; } } ").VerifyDiagnostics( // (11,51): error CS1938: The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on 5 equals a // CS1938 Diagnostic(ErrorCode.ERR_QueryInnerKey, "a").WithArguments("a") ); } [Fact] public void CS1939ERR_QueryOutRefRangeVariable() { var text = @" using System.Linq; class Test { public static int F(ref int i) { return i; } public static void Main() { var list = new int[] { 0, 1, 2, 3, 4, 5 }; var q = from x in list let k = x select Test.F(ref x); // CS1939 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,35): error CS1939: Cannot pass the range variable 'x' as an out or ref parameter // select Test.F(ref x); // CS1939 Diagnostic(ErrorCode.ERR_QueryOutRefRangeVariable, "x").WithArguments("x")); } [Fact] public void CS1940ERR_QueryMultipleProviders() { var text = @"using System; class Test { public delegate int Dele(int x); int num = 0; public int Select(Func<int, int> d) { return d(this.num); } public int Select(Dele d) { return d(this.num) + 1; } public static void Main() { var q = from x in new Test() select x; // CS1940 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (18,17): error CS1940: Multiple implementations of the query pattern were found for source type 'Test'. Ambiguous call to 'Select'. // select Diagnostic(ErrorCode.ERR_QueryMultipleProviders, "select x").WithArguments("Test", "Select") ); } [Fact] public void CS1941ERR_QueryTypeInferenceFailedMulti() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { var nums = new int[] { 1, 2, 3, 4, 5, 6 }; var words = new string[] { ""lake"", ""mountain"", ""sky"" }; IEnumerable e = from n in nums join w in words on n equals w // CS1941 select w; return 0; } } ").VerifyDiagnostics( // (11,25): error CS1941: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. // join Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedMulti, "join").WithArguments("join", "Join")); } [Fact] public void CS1942ERR_QueryTypeInferenceFailed() { var text = @" using System; class Q { public Q Select<T,U>(Func<int, int> func) { return this; } } class Program { static void Main(string[] args) { var x = from i in new Q() select i; //CS1942 } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,17): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'. // select i; //CS1942 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, "select").WithArguments("select", "Select") ); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { class TestClass { } static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; TestClass tc = new TestClass(); var x = from n in nums from s in tc // CS1943 select n + s; } } ").VerifyDiagnostics( // (13,27): error CS1943: An expression of type 'Test.TestClass' is not allowed in a subsequent from clause in a query expression with source type 'int[]'. Type inference failed in the call to 'SelectMany'. // tc Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "tc").WithArguments("Test.TestClass", "int[]", "SelectMany")); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System; class Test { class F1 { public F1 SelectMany<T, U>(Func<int, F1> func1, Func<int, int> func2) { return this; } } static void Main() { F1 f1 = new F1(); var x = from f in f1 from g in 3 select f + g; } } ").VerifyDiagnostics( // (14,23): error CS1943: An expression of type 'int' is not allowed in a subsequent from clause in a query expression with source type 'Test.F1'. Type inference failed in the call to 'SelectMany'. // from g in 3 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "3").WithArguments("int", "Test.F1", "SelectMany").WithLocation(14, 23) ); } [Fact, WorkItem(546510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546510")] public void CS1944ERR_ExpressionTreeContainsPointerOp() { var text = @" using System; using System.Linq.Expressions; unsafe class Test { public delegate int* D(int i); static void Main() { Expression<D> tree = x => &x; // CS1944 Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; } } "; //Assert.Equal("", text); CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,35): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<D> tree = x => &x; // CS1944 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x"), // (11,68): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x") ); } [Fact] public void CS1945ERR_ExpressionTreeContainsAnonymousMethod() { var text = @" using System; using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,61): error CS1945: An expression tree may not contain an anonymous method expression // Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, "delegate(int i) { return true; }") ); } [Fact] public void CS1946ERR_AnonymousMethodToExpressionTree() { var text = @" using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<D> tree = delegate() { }; //CS1946 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // Expression<D> tree = delegate() { }; //CS1946 Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate() { }") ); } [Fact] public void CS1947ERR_QueryRangeVariableReadOnly() { var program = @" using System.Linq; class Test { static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; var x = from i in array let k = i select i = 5; // CS1947 x.ToList(); } } "; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "i").WithArguments("i")); } [Fact] public void CS1948ERR_QueryRangeVariableSameAsTypeParam() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { public void TestMethod<T>(T t) { var x = from T in Enumerable.Range(1, 100) // CS1948 select T; } public static void Main() { } } ").VerifyDiagnostics( // (8,17): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T")); } [Fact] public void CS1949ERR_TypeVarNotFoundRangeVariable() { var text = @"using System.Linq; class Test { static void Main() { var x = from var i in Enumerable.Range(1, 100) // CS1949 select i; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,22): error CS1949: The contextual keyword 'var' cannot be used in a range variable declaration // var x = from var i in Enumerable.Range(1, 100) // CS1949 Diagnostic(ErrorCode.ERR_TypeVarNotFoundRangeVariable, "var") ); } // CS1950 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1951ERR_ByRefParameterInExpressionTree() { var text = @" public delegate int TestDelegate(ref int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,75): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 75) ); } [Fact] public void CS1951ERR_InParameterInExpressionTree() { var text = @" public delegate int TestDelegate(in int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,74): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 74) ); } [Fact] public void CS1952ERR_VarArgsInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class Test { public static int M(__arglist) { return 1; } static int Main() { Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,52): error CS1952: An expression tree lambda may not contain a method with variable arguments // Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, "__arglist(x)") ); } [WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] [Fact] public void CS1953ERR_MemGroupInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class CS1953 { public static void Main() { double num = 10; Expression<Func<bool>> testExpr = () => num.GetType is int; // CS0837 } }"; // Used to be CS1953, but now a method group in an is expression is illegal anyway. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,21): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // () => num.GetType is int; // CS1953 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "num.GetType is int").WithLocation(10, 21)); } // CS1954 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1955ERR_NonInvocableMemberCalled() { var text = @" namespace CompilerError1955 { class ClassA { public int x = 100; public int X { get { return x; } set { x = value; } } } class Test { static void Main() { ClassA a = new ClassA(); System.Console.WriteLine(a.x()); // CS1955 System.Console.WriteLine(a.X()); // CS1955 } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 19, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 20, Column = 40 }}); } // CS1958 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1959ERR_InvalidConstantDeclarationType() { var text = @" class Program { static void Test<T>() where T : class { const T x = null; // CS1959 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS1959: 'x' is of type 'T'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. // const T x = null; // CS1959 Diagnostic(ErrorCode.ERR_InvalidConstantDeclarationType, "null").WithArguments("x", "T") ); } /// <summary> /// Test the different contexts in which CS1961 can be seen. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Contexts() { var text = @" interface IContexts<in TIn, out TOut, TInv> { #region In TIn Property1In { set; } TIn Property2In { get; } //CS1961 on ""TIn"" TIn Property3In { get; set; } //CS1961 on ""TIn"" int this[TIn arg, char filler, char indexer1In] { get; } TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on ""TIn"" int this[TIn arg, bool filler, char indexer3In] { set; } TIn this[int arg, bool[] filler, char indexer4In] { set; } int this[TIn arg, long filler, char indexer5In] { get; set; } TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on ""TIn"" int Method1In(TIn p); TIn Method2In(); //CS1961 on ""TIn"" int Method3In(out TIn p); //CS1961 on ""TIn"" int Method4In(ref TIn p); //CS1961 on ""TIn"" event DOut<TIn> Event1In; #endregion In #region Out TOut Property1Out { set; } //CS1961 on ""TOut"" TOut Property2Out { get; } TOut Property3Out { get; set; } //CS1961 on ""TOut"" int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on ""TOut"" TOut this[int arg, char[] filler, bool indexer2Out] { get; } int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on ""TOut"" TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on ""TOut"" int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on ""TOut"" TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on ""TOut"" long Method1Out(TOut p); //CS1961 on ""TOut"" TOut Method2Out(); long Method3Out(out TOut p); //CS1961 on ""TOut"" (sic: out params have to be input-safe) long Method4Out(ref TOut p); //CS1961 on ""TOut"" event DOut<TOut> Event1Out; //CS1961 on ""TOut"" #endregion Out #region Inv TInv Property1Inv { set; } TInv Property2Inv { get; } TInv Property3Inv { get; set; } int this[TInv arg, char filler, long indexer1Inv] { get; } TInv this[int arg, char[] filler, long indexer2Inv] { get; } int this[TInv arg, bool filler, long indexer3Inv] { set; } TInv this[int arg, bool[] filler, long indexer4Inv] { set; } int this[TInv arg, long filler, long indexer5Inv] { get; set; } TInv this[int arg, long[] filler, long indexer6Inv] { get; set; } long Method1Inv(TInv p); TInv Method2Inv(); long Method3Inv(out TInv p); long Method4Inv(ref TInv p); event DOut<TInv> Event1Inv; #endregion Inv } delegate void DOut<out T>(); //for event types - should preserve the variance of the type arg "; CreateCompilation(text).VerifyDiagnostics( // (6,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Property2In'. 'TIn' is contravariant. // TIn Property2In { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property2In", "TIn", "contravariant", "covariantly").WithLocation(6, 5), // (7,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3In'. 'TIn' is contravariant. // TIn Property3In { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property3In", "TIn", "contravariant", "invariantly").WithLocation(7, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, char[], char]'. 'TIn' is contravariant. // TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, char[], char]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (14,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], char]'. 'TIn' is contravariant. // TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], char]", "TIn", "contravariant", "invariantly").WithLocation(14, 5), // (17,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Method2In()'. 'TIn' is contravariant. // TIn Method2In(); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method2In()", "TIn", "contravariant", "covariantly").WithLocation(17, 5), // (18,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3In(out TIn)'. 'TIn' is contravariant. // int Method3In(out TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method3In(out TIn)", "TIn", "contravariant", "invariantly").WithLocation(18, 23), // (19,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4In(ref TIn)'. 'TIn' is contravariant. // int Method4In(ref TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method4In(ref TIn)", "TIn", "contravariant", "invariantly").WithLocation(19, 23), // (25,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Property1Out'. 'TOut' is covariant. // TOut Property1Out { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property1Out", "TOut", "covariant", "contravariantly").WithLocation(25, 5), // (27,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3Out'. 'TOut' is covariant. // TOut Property3Out { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property3Out", "TOut", "covariant", "invariantly").WithLocation(27, 5), // (29,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, char, bool]'. 'TOut' is covariant. // int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, char, bool]", "TOut", "covariant", "contravariantly").WithLocation(29, 14), // (31,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]'. 'TOut' is covariant. // int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]", "TOut", "covariant", "contravariantly").WithLocation(31, 14), // (32,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, bool[], bool]'. 'TOut' is covariant. // TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, bool[], bool]", "TOut", "covariant", "contravariantly").WithLocation(32, 5), // (33,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, long, bool]'. 'TOut' is covariant. // int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, long, bool]", "TOut", "covariant", "contravariantly").WithLocation(33, 14), // (34,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], bool]'. 'TOut' is covariant. // TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], bool]", "TOut", "covariant", "invariantly").WithLocation(34, 5), // (36,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Method1Out(TOut)'. 'TOut' is covariant. // long Method1Out(TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method1Out(TOut)", "TOut", "covariant", "contravariantly").WithLocation(36, 21), // (38,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3Out(out TOut)'. 'TOut' is covariant. // long Method3Out(out TOut p); //CS1961 on "TOut" (sic: out params have to be input-safe) Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method3Out(out TOut)", "TOut", "covariant", "invariantly").WithLocation(38, 25), // (39,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)'. 'TOut' is covariant. // long Method4Out(ref TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)", "TOut", "covariant", "invariantly").WithLocation(39, 25), // (41,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Event1Out'. 'TOut' is covariant. // event DOut<TOut> Event1Out; //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event1Out").WithArguments("IContexts<TIn, TOut, TInv>.Event1Out", "TOut", "covariant", "contravariantly").WithLocation(41, 22)); } /// <summary> /// Test all of the contexts that require output safety. /// Note: some also require input safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_OutputUnsafe() { var text = @" interface IOutputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { get; } TInv this[long[] Indexer1Good] { get; } TInv Method1Good(); TIn Property1Bad { get; } TIn this[char[] Indexer1Bad] { get; } TIn Method1Bad(); #endregion Case 1 #region Case 2: array of output-unsafe TInv[] Property2Good { get; } TInv[] this[long[,] Indexer2Good] { get; } TInv[] Method2Good(); TIn[] Property2Bad { get; } TIn[] this[char[,] Indexer2Bad] { get; } TIn[] Method2Bad(); #endregion Case 2 #region Case 3: constructed with output-unsafe type arg in covariant slot IOut<TInv> Property3Good { get; } IOut<TInv> this[long[,,] Indexer3Good] { get; } IOut<TInv> Method3Good(); IOut<TIn> Property3Bad { get; } IOut<TIn> this[char[,,] Indexer3Bad] { get; } IOut<TIn> Method3Bad(); #endregion Case 3 #region Case 4: constructed with output-unsafe type arg in invariant slot IInv<TInv> Property4Good { get; } IInv<TInv> this[long[,,,] Indexer4Good] { get; } IInv<TInv> Method4Good(); IInv<TIn> Property4Bad { get; } IInv<TIn> this[char[,,,] Indexer4Bad] { get; } IInv<TIn> Method4Bad(); #endregion Case 4 #region Case 5: constructed with input-unsafe (sic) type arg in contravariant slot IIn<TInv> Property5Good { get; } IIn<TInv> this[long[,,,,] Indexer5Good] { get; } IIn<TInv> Method5Good(); IIn<TOut> Property5Bad { get; } IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } IIn<TOut> Method5Bad(); #endregion Case 5 #region Case 6: constructed with input-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { get; } IInv<TInv> this[long[,,,,,] Indexer6Good] { get; } IInv<TInv> Method6Good(); IInv<TOut> Property6Bad { get; } IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } IInv<TOut> Method6Bad(); #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (9,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TIn' is contravariant. // TIn Property1Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property1Bad", "TIn", "contravariant", "covariantly").WithLocation(9, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TIn' is contravariant. // TIn this[char[] Indexer1Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[]]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (11,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()'. 'TIn' is contravariant. // TIn Method1Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()", "TIn", "contravariant", "covariantly").WithLocation(11, 5), // (19,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TIn' is contravariant. // TIn[] Property2Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property2Bad", "TIn", "contravariant", "covariantly").WithLocation(19, 5), // (20,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TIn' is contravariant. // TIn[] this[char[,] Indexer2Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TIn", "contravariant", "covariantly").WithLocation(20, 5), // (21,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()'. 'TIn' is contravariant. // TIn[] Method2Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()", "TIn", "contravariant", "covariantly").WithLocation(21, 5), // (29,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TIn' is contravariant. // IOut<TIn> Property3Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property3Bad", "TIn", "contravariant", "covariantly").WithLocation(29, 5), // (30,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TIn' is contravariant. // IOut<TIn> this[char[,,] Indexer3Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(30, 5), // (31,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()'. 'TIn' is contravariant. // IOut<TIn> Method3Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()", "TIn", "contravariant", "covariantly").WithLocation(31, 5), // (39,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TIn' is contravariant. // IInv<TIn> Property4Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property4Bad", "TIn", "contravariant", "invariantly").WithLocation(39, 5), // (40,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,] Indexer4Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(40, 5), // (41,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()'. 'TIn' is contravariant. // IInv<TIn> Method4Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()", "TIn", "contravariant", "invariantly").WithLocation(41, 5), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TOut' is covariant. // IIn<TOut> Property5Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property5Bad", "TOut", "covariant", "contravariantly").WithLocation(49, 5), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TOut' is covariant. // IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(50, 5), // (51,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()'. 'TOut' is covariant. // IIn<TOut> Method5Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()", "TOut", "covariant", "contravariantly").WithLocation(51, 5), // (59,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TOut' is covariant. // IInv<TOut> Property6Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property6Bad", "TOut", "covariant", "invariantly").WithLocation(59, 5), // (60,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(60, 5), // (61,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()'. 'TOut' is covariant. // IInv<TOut> Method6Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()", "TOut", "covariant", "invariantly").WithLocation(61, 5)); } /// <summary> /// Test all of the contexts that require input safety. /// Note: some also require output safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_InputUnsafe() { var text = @" interface IInputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { set; } TInv this[long[] Indexer1GoodA] { set; } long this[long[] Indexer1GoodB, TInv p] { set; } long Method1Good(TInv p); TOut Property1Bad { set; } TOut this[char[] Indexer1BadA] { set; } long this[char[] Indexer1BadB, TOut p] { set; } long Method1Bad(TOut p); #endregion Case 1 #region Case 2: array of input-unsafe TInv[] Property2Good { set; } TInv[] this[long[,] Indexer2GoodA] { set; } long this[long[,] Indexer2GoodB, TInv[] p] { set; } long Method2Good(TInv[] p); TOut[] Property2Bad { set; } TOut[] this[char[,] Indexer2BadA] { set; } long this[char[,] Indexer2BadB, TOut[] p] { set; } long Method2Bad(TOut[] p); #endregion Case 2 #region Case 3: constructed with input-unsafe type arg in covariant (sic: not flipped) slot IOut<TInv> Property3Good { set; } IOut<TInv> this[long[,,] Indexer3GoodA] { set; } long this[long[,,] Indexer3GoodB, IOut<TInv> p] { set; } long Method3Good(IOut<TInv> p); event DOut<TInv> Event3Good; IOut<TOut> Property3Bad { set; } IOut<TOut> this[char[,,] Indexer3BadA] { set; } long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } long Method3Bad(IOut<TOut> p); event DOut<TOut> Event3Bad; #endregion Case 3 #region Case 4: constructed with input-unsafe type arg in invariant slot IInv<TInv> Property4Good { set; } IInv<TInv> this[long[,,,] Indexer4GoodA] { set; } long this[long[,,,] Indexer4GoodB, IInv<TInv> p] { set; } long Method4Good(IInv<TInv> p); event DInv<TInv> Event4Good; IInv<TOut> Property4Bad { set; } IInv<TOut> this[char[,,,] Indexer4BadA] { set; } long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } long Method4Bad(IInv<TOut> p); event DInv<TOut> Event4Bad; #endregion Case 4 #region Case 5: constructed with output-unsafe (sic) type arg in contravariant (sic: not flipped) slot IIn<TInv> Property5Good { set; } IIn<TInv> this[long[,,,,] Indexer5GoodA] { set; } long this[long[,,,,] Indexer5GoodB, IIn<TInv> p] { set; } long Method5Good(IIn<TInv> p); event DIn<TInv> Event5Good; IIn<TIn> Property5Bad { set; } IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } long Method5Bad(IIn<TIn> p); event DIn<TIn> Event5Bad; #endregion Case 5 #region Case 6: constructed with output-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { set; } IInv<TInv> this[long[,,,,,] Indexer6GoodA] { set; } long this[long[,,,,,] Indexer6GoodB, IInv<TInv> p] { set; } long Method6Good(IInv<TInv> p); event DInv<TInv> Event6Good; IInv<TIn> Property6Bad { set; } IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } long Method6Bad(IInv<TIn> p); event DInv<TIn> Event6Bad; #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { } delegate void DIn<in T>(); delegate void DOut<out T>(); delegate void DInv<T>(); "; CreateCompilation(text).VerifyDiagnostics( // (11,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TOut' is covariant. // TOut this[char[] Indexer1BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[]]", "TOut", "covariant", "contravariantly").WithLocation(11, 5), // (12,36): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]'. 'TOut' is covariant. // long this[char[] Indexer1BadB, TOut p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]", "TOut", "covariant", "contravariantly").WithLocation(12, 36), // (23,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TOut' is covariant. // TOut[] this[char[,] Indexer2BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TOut", "covariant", "contravariantly").WithLocation(23, 5), // (24,37): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]'. 'TOut' is covariant. // long this[char[,] Indexer2BadB, TOut[] p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]", "TOut", "covariant", "contravariantly").WithLocation(24, 37), // (36,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TOut' is covariant. // IOut<TOut> this[char[,,] Indexer3BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(36, 5), // (37,38): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]'. 'TOut' is covariant. // long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]", "TOut", "covariant", "contravariantly").WithLocation(37, 38), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,] Indexer4BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(50, 5), // (51,39): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]'. 'TOut' is covariant. // long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]", "TOut", "covariant", "invariantly").WithLocation(51, 39), // (64,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TIn' is contravariant. // IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(64, 5), // (65,40): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]", "TIn", "contravariant", "covariantly").WithLocation(65, 40), // (78,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(78, 5), // (79,41): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]", "TIn", "contravariant", "invariantly").WithLocation(79, 41), // (10,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TOut' is covariant. // TOut Property1Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property1Bad", "TOut", "covariant", "contravariantly").WithLocation(10, 5), // (13,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)'. 'TOut' is covariant. // long Method1Bad(TOut p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)", "TOut", "covariant", "contravariantly").WithLocation(13, 21), // (22,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TOut' is covariant. // TOut[] Property2Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property2Bad", "TOut", "covariant", "contravariantly").WithLocation(22, 5), // (25,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])'. 'TOut' is covariant. // long Method2Bad(TOut[] p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])", "TOut", "covariant", "contravariantly").WithLocation(25, 21), // (35,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TOut' is covariant. // IOut<TOut> Property3Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property3Bad", "TOut", "covariant", "contravariantly").WithLocation(35, 5), // (38,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)'. 'TOut' is covariant. // long Method3Bad(IOut<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)", "TOut", "covariant", "contravariantly").WithLocation(38, 21), // (39,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event3Bad'. 'TOut' is covariant. // event DOut<TOut> Event3Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event3Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event3Bad", "TOut", "covariant", "contravariantly").WithLocation(39, 22), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TOut' is covariant. // IInv<TOut> Property4Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property4Bad", "TOut", "covariant", "invariantly").WithLocation(49, 5), // (52,21): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)'. 'TOut' is covariant. // long Method4Bad(IInv<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)", "TOut", "covariant", "invariantly").WithLocation(52, 21), // (53,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event4Bad'. 'TOut' is covariant. // event DInv<TOut> Event4Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event4Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event4Bad", "TOut", "covariant", "invariantly").WithLocation(53, 22), // (63,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TIn' is contravariant. // IIn<TIn> Property5Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property5Bad", "TIn", "contravariant", "covariantly").WithLocation(63, 5), // (66,21): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)'. 'TIn' is contravariant. // long Method5Bad(IIn<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)", "TIn", "contravariant", "covariantly").WithLocation(66, 21), // (67,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event5Bad'. 'TIn' is contravariant. // event DIn<TIn> Event5Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event5Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event5Bad", "TIn", "contravariant", "covariantly").WithLocation(67, 20), // (77,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TIn' is contravariant. // IInv<TIn> Property6Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property6Bad", "TIn", "contravariant", "invariantly").WithLocation(77, 5), // (80,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)'. 'TIn' is contravariant. // long Method6Bad(IInv<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)", "TIn", "contravariant", "invariantly").WithLocation(80, 21), // (81,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event6Bad'. 'TIn' is contravariant. // event DInv<TIn> Event6Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event6Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event6Bad", "TIn", "contravariant", "invariantly").WithLocation(81, 21)); } /// <summary> /// Test output-safety checks on base interfaces. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_BaseInterfaces() { var text = @" interface IBaseInterfaces<in TIn, out TOut, TInv> : IIn<TOut>, IOut<TIn>, IInv<TInv> { } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IIn<TOut>'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IIn<TOut>", "TOut", "covariant", "contravariantly"), // (2,30): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOut<TIn>'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOut<TIn>", "TIn", "contravariant", "covariantly")); } /// <summary> /// Test all type parameter/type argument combinations. /// | Type Arg Covariant | Type Arg Contravariant | Type Arg Invariant /// -------------------------+----------------------+------------------------+-------------------- /// Type Param Covariant | Covariant | Contravariant | Invariant /// Type Param Contravariant | Contravariant | Covariant | Invariant /// Type Param Invariant | Error | Error | Invariant /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Generics() { var text = @" interface IOutputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { ICovariant<TInputUnsafe> OutputUnsafe1(); ICovariant<TOutputUnsafe> OutputUnsafe2(); ICovariant<TInvariant> OutputUnsafe3(); IContravariant<TInputUnsafe> OutputUnsafe4(); IContravariant<TOutputUnsafe> OutputUnsafe5(); IContravariant<TInvariant> OutputUnsafe6(); IInvariant<TInputUnsafe> OutputUnsafe7(); IInvariant<TOutputUnsafe> OutputUnsafe8(); IInvariant<TInvariant> OutputUnsafe9(); } interface IInputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ICovariant<TInputUnsafe> p); void InputUnsafe2(ICovariant<TOutputUnsafe> p); void InputUnsafe3(ICovariant<TInvariant> p); void InputUnsafe4(IContravariant<TInputUnsafe> p); void InputUnsafe5(IContravariant<TOutputUnsafe> p); void InputUnsafe6(IContravariant<TInvariant> p); void InputUnsafe7(IInvariant<TInputUnsafe> p); void InputUnsafe8(IInvariant<TOutputUnsafe> p); void InputUnsafe9(IInvariant<TInvariant> p); } interface IBothUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ref ICovariant<TInputUnsafe> p); void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); void InputUnsafe3(ref ICovariant<TInvariant> p); void InputUnsafe4(ref IContravariant<TInputUnsafe> p); void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); void InputUnsafe6(ref IContravariant<TInvariant> p); void InputUnsafe7(ref IInvariant<TInputUnsafe> p); void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); void InputUnsafe9(ref IInvariant<TInvariant> p); } interface ICovariant<out T> { } interface IContravariant<in T> { } interface IInvariant<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()'. 'TOutputUnsafe' is contravariant. // ICovariant<TOutputUnsafe> OutputUnsafe2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(5, 5), // (8,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()'. 'TInputUnsafe' is covariant. // IContravariant<TInputUnsafe> OutputUnsafe4(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()", "TInputUnsafe", "covariant", "contravariantly").WithLocation(8, 5), // (12,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()'. 'TInputUnsafe' is covariant. // IInvariant<TInputUnsafe> OutputUnsafe7(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()", "TInputUnsafe", "covariant", "invariantly").WithLocation(12, 5), // (13,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()'. 'TOutputUnsafe' is contravariant. // IInvariant<TOutputUnsafe> OutputUnsafe8(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(13, 5), // (19,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "contravariantly").WithLocation(19, 23), // (24,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(24, 23), // (27,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(27, 23), // (28,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(28, 23), // Dev10 doesn't say "must be invariantly valid" for ref params - it lists whichever check fails first. This approach seems nicer. // (34,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ref ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(34, 27), // (35,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(35, 27), // (38,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe4(ref IContravariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(38, 27), // (39,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(39, 27), // (42,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(ref IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(42, 27), // (43,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(43, 27)); } [Fact] public void CS1961ERR_UnexpectedVariance_DelegateInvoke() { var text = @" delegate TIn D1<in TIn>(); //CS1961 delegate TOut D2<out TOut>(); delegate T D3<T>(); delegate void D4<in TIn>(TIn p); delegate void D5<out TOut>(TOut p); //CS1961 delegate void D6<T>(T p); delegate void D7<in TIn>(ref TIn p); //CS1961 delegate void D8<out TOut>(ref TOut p); //CS1961 delegate void D9<T>(ref T p); delegate void D10<in TIn>(out TIn p); //CS1961 delegate void D11<out TOut>(out TOut p); //CS1961 delegate void D12<T>(out T p); "; CreateCompilation(text).VerifyDiagnostics( // (2,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'D1<TIn>.Invoke()'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D1<TIn>.Invoke()", "TIn", "contravariant", "covariantly"), // (7,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'D5<TOut>.Invoke(TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D5<TOut>.Invoke(TOut)", "TOut", "covariant", "contravariantly"), // (10,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D7<TIn>.Invoke(ref TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D7<TIn>.Invoke(ref TIn)", "TIn", "contravariant", "invariantly"), // (11,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D8<TOut>.Invoke(ref TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D8<TOut>.Invoke(ref TOut)", "TOut", "covariant", "invariantly"), // (14,22): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D10<TIn>.Invoke(out TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D10<TIn>.Invoke(out TIn)", "TIn", "contravariant", "invariantly"), // (15,23): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D11<TOut>.Invoke(out TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D11<TOut>.Invoke(out TOut)", "TOut", "covariant", "invariantly")); } [Fact] public void CS1962ERR_BadDynamicTypeof() { var text = @" public class C { public static int Main() { dynamic S = typeof(dynamic); return 0; } public static int Test(int age) { return 1; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS1962: The typeof operator cannot be used on the dynamic type Diagnostic(ErrorCode.ERR_BadDynamicTypeof, "typeof(dynamic)")); } [Fact] [WorkItem(54804, "https://github.com/dotnet/roslyn/issues/54804")] public void BadNestedTypeof() { var source = @" #nullable enable using System; using System.Collections.Generic; var x = typeof(List<dynamic>); // 1 x = typeof(nint); // 2 x = typeof(List<nint>); // 3 x = typeof(List<string?>); // 4 x = typeof((int a, int b)); // 5 x = typeof((int a, string? b)); // 6 x = typeof(ValueTuple<int, int>); // ok "; CreateCompilation(source).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.DebugExe.WithWarningLevel(5)).VerifyDiagnostics(); } // CS1963ERR_ExpressionTreeContainsDynamicOperation --> SyntaxBinderTests [Fact] public void CS1964ERR_BadDynamicConversion() { var text = @" class A { public static implicit operator dynamic(A a) { return a; } public static implicit operator A(dynamic a) { return a; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,37): error CS1964: 'A.implicit operator A(dynamic)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "A").WithArguments("A.implicit operator A(dynamic)"), // (4,37): error CS1964: 'A.implicit operator dynamic(A)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("A.implicit operator dynamic(A)")); } // CS1969ERR_DynamicRequiredTypesMissing -> CodeGen_DynamicTests.Missing_* // CS1970ERR_ExplicitDynamicAttr --> AttributeTests_Dynamic.ExplicitDynamicAttribute [Fact] public void CS1971ERR_NoDynamicPhantomOnBase() { const string text = @" public class B { public virtual void M(object o) {} } public class D : B { public override void M(object o) {} void N(dynamic d) { base.M(d); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,9): error CS1971: The call to method 'M' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // base.M(d); Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBase, "base.M(d)").WithArguments("M")); } [Fact] public void CS1972ERR_NoDynamicPhantomOnBaseIndexer() { const string text = @" public class B { public string this[int index] { get { return ""You passed "" + index; } } } public class D : B { public void M(object o) { int[] arr = { 1, 2, 3 }; int s = base[(dynamic)o]; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (14,17): error CS1972: The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // int s = base[(dynamic)o]; Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, "base[(dynamic)o]")); } [Fact] public void CS1973ERR_BadArgTypeDynamicExtension() { const string text = @" class Program { static void Main() { dynamic d = 1; B b = new B(); b.Goo(d); } } public class B { } static public class Extension { public static void Goo(this B b, int x) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (8,9): error CS1973: 'B' has no applicable method named 'Goo' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. // b.Goo(d); Diagnostic(ErrorCode.ERR_BadArgTypeDynamicExtension, "b.Goo(d)").WithArguments("B", "Goo")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_Base() { var text = @" class A { public A(int x) { } } class B : A { public B(dynamic d) : base(d) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "base")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_This() { var text = @" class B { public B(dynamic d) : this(d, 1) { } public B(int a, int b) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "this")); } [Fact] public void CS1976ERR_BadDynamicMethodArgMemgrp() { const string text = @" class Program { static void M(dynamic d) { d.Goo(M); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // d.Goo(M); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "M")); } [Fact] public void CS1977ERR_BadDynamicMethodArgLambda() { const string text = @" class Program { static void M(dynamic d) { d.Goo(()=>{}); d.Goo(delegate () {}); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // d.Goo(()=>{}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "()=>{}"), // (7,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // d.Goo(delegate () {}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate () {}")); } [Fact, WorkItem(578352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578352")] public void CS1977ERR_BadDynamicMethodArgLambda_CreateObject() { string source = @" using System; class C { static void Main() { dynamic y = null; new C(delegate { }, y); } public C(Action a, Action y) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }); comp.VerifyDiagnostics( // (9,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }")); } [Fact] public void CS1660ERR_BadDynamicMethodArgLambda_CollectionInitializer() { string source = @" using System; using System.Collections; using System.Collections.Generic; unsafe class C : IEnumerable<object> { public static void M(__arglist) { int a; int* p = &a; dynamic d = null; var c = new C { { d, delegate() { } }, { d, 1, p }, { d, __arglist }, { d, GetEnumerator }, { d, SomeStaticMethod }, }; } public static void SomeStaticMethod() {} public void Add(dynamic d, int x, int* ptr) { } public void Add(dynamic d, RuntimeArgumentHandle x) { } public void Add(dynamic d, Action f) { } public void Add(dynamic d, Func<IEnumerator<object>> f) { } public IEnumerator<object> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (16,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // { d, delegate() { } }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate() { }").WithLocation(16, 18), // (17,21): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. // { d, 1, p }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "p").WithArguments("int*").WithLocation(17, 21), // (18,18): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation. // { d, __arglist }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 18), // (19,13): error CS1950: The best overloaded Add method 'C.Add(dynamic, RuntimeArgumentHandle)' for the collection initializer has some invalid arguments // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, "{ d, GetEnumerator }").WithArguments("C.Add(dynamic, System.RuntimeArgumentHandle)").WithLocation(19, 13), // (19,18): error CS1503: Argument 2: cannot convert from 'method group' to 'RuntimeArgumentHandle' // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgType, "GetEnumerator").WithArguments("2", "method group", "System.RuntimeArgumentHandle").WithLocation(19, 18), // (20,18): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // { d, SomeStaticMethod }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "SomeStaticMethod").WithLocation(20, 18)); } [Fact] public void CS1978ERR_BadDynamicMethodArg() { // The dev 10 compiler gives arguably wrong error here; it says that "TypedReference may not be // used as a type argument". Though that is true, and though what is happening here behind the scenes // is that TypedReference is being used as a type argument to a dynamic call site helper method, // that's giving an error about an implementation detail. A better error is to say that // TypedReference is not a legal type in a dynamic operation. // // Dev10 compiler didn't report an error for by-ref pointer argument. See Dev10 bug 819498. // The error should be reported for any pointer argument regardless of its refness. const string text = @" class Program { unsafe static void M(dynamic d, int* i, System.TypedReference tr) { d.Goo(i); d.Goo(tr); d.Goo(ref tr); d.Goo(out tr); d.Goo(out i); d.Goo(ref i); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,15): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (7,15): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (8,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (9,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (10,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (11,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*")); } // CS1979ERR_BadDynamicQuery --> DynamicTests.cs, DynamicQuery_* // Test CS1980ERR_DynamicAttributeMissing moved to AttributeTests_Dynamic.cs // CS1763 is covered for different code path by SymbolErrorTests.CS1763ERR_NotNullRefDefaultParameter() [WorkItem(528854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528854")] [Fact] public void CS1763ERR_NotNullRefDefaultParameter02() { string text = @" class Program { public void Goo<T, U>(T t = default(U)) where U : T { } static void Main(string[] args) { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS1763: 't' is of type 'T'. A default parameter value of a reference type other than string can only be initialized with null // public void Goo<T, U>(T t = default(U)) where U : T Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "t").WithArguments("t", "T")); } #endregion #region "Targeted Warning Tests - please arrange tests in the order of error code" [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent() { var text = @" delegate void MyDelegate(); class MyClass { public event MyDelegate evt; // CS0067 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,29): warning CS0067: The event 'MyClass.evt' is never used // public event MyDelegate evt; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "evt").WithArguments("MyClass.evt")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessibility() { var text = @" using System; class MyClass { public event Action E1; // CS0067 internal event Action E2; // CS0067 protected internal event Action E3; // CS0067 protected event Action E4; // CS0067 private event Action E5; // CS0067 } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): warning CS0067: The event 'MyClass.E1' is never used // public event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("MyClass.E1"), // (6,27): warning CS0067: The event 'MyClass.E2' is never used // internal event Action E2; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("MyClass.E2"), // (7,37): warning CS0067: The event 'MyClass.E3' is never used // protected internal event Action E3; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("MyClass.E3"), // (8,28): warning CS0067: The event 'MyClass.E4' is never used // protected event Action E4; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("MyClass.E4"), // (9,26): warning CS0067: The event 'MyClass.E5' is never used // private event Action E5; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E5").WithArguments("MyClass.E5")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_StructLayout() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { event Action E1; } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Kind() { var text = @" using System; class C { event Action E1; // CS0067 event Action E2 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0067: The event 'C.E1' is never used // event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessed() { var text = @" using System; class C { event Action None; // CS0067 event Action Read; event Action Write; event Action Add; // CS0067 void M(Action a) { M(Read); Write = a; Add += a; } } "; CreateCompilation(text).VerifyDiagnostics( // (9,18): warning CS0067: The event 'C.Add' is never used // event Action Add; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Add").WithArguments("C.Add"), // (6,18): warning CS0067: The event 'C.None' is never used // event Action None; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "None").WithArguments("C.None")); } [Fact, WorkItem(581002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581002")] public void CS0067WRN_UnreferencedEvent_Virtual() { var text = @"class A { public virtual event System.EventHandler B; class C : A { public override event System.EventHandler B; } static int Main() { C c = new C(); A a = c; return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,46): warning CS0067: The event 'A.B' is never used // public virtual event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.B"), // (6,51): warning CS0067: The event 'A.C.B' is never used // public override event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.C.B")); } [Fact, WorkItem(539630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539630")] public void CS0162WRN_UnreachableCode01() { var text = @" class MyTest { } class MyClass { const MyTest test = null; public static int Main() { goto lab1; { // The following statements cannot be reached: int i = 9; // CS0162 i++; } lab1: if (test == null) { return 0; } else { return 1; // CS0162 } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "int"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(530037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530037")] public void CS0162WRN_UnreachableCode02() { var text = @" using System; public class Test { public static void Main(string[] args) { // (1) do { for (; ; ) { } } while (args.Length > 0); // Native CS0162 // (2) for (; ; ) // Roslyn CS0162 { goto L2; Console.WriteLine(""Unreachable code""); L2: // Roslyn CS0162 break; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,5): warning CS0162: Unreachable code detected // for (; ; ) // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "for"), // (18,5): warning CS0162: Unreachable code detected // L2: // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "L2") ); } [Fact, WorkItem(539873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539873"), WorkItem(539981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539981")] public void CS0162WRN_UnreachableCode04() { var text = @" public class Cls { public static int Main() { goto Label2; return 0; Label1: return 1; Label2: goto Label1; return 2; } delegate void Sub_0(); static void M() { Sub_0 s1_3 = () => { if (2 == 1) return; else return; }; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(540901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540901")] public void CS0162WRN_UnreachableCode06_Loops() { var text = @" class Program { void F() { } void T() { for (int i = 0; i < 0; F(), i++) // F() is unreachable { return; } } static void Main() { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { goto stop; System.Console.WriteLine(y); // unreachable } foreach (char y in x) { throw new System.Exception(); System.Console.WriteLine(y); // unreachable } stop: return; } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "F"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode06_Foreach03() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { return; System.Console.WriteLine(y); } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode07_GotoInLambda() { var text = @" using System; class Program { static void Main() { Action a = () => { goto label1; Console.WriteLine(""unreachable""); label1: Console.WriteLine(""reachable""); }; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, @"Console")); } [Fact] public void CS0164WRN_UnreferencedLabel() { var text = @" public class a { public int i = 0; public static void Main() { int i = 0; // CS0164 l1: i++; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(9, 7)); } [Fact] public void CS0168WRN_UnreferencedVar01() { var text = @" public class clx { public int i; } public class clz { public static void Main() { int j ; // CS0168, uncomment the following line // j++; clx a; // CS0168, try the following line instead // clx a = new clx(); } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(11, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(13, 13)); } [Fact] public void CS0168WRN_UnreferencedVar02() { var text = @"using System; class C { static void M() { try { } catch (InvalidOperationException e) { } catch (InvalidCastException e) { throw; } catch (Exception e) { throw e; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(7, 42), Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(8, 37)); } [Fact] public void CS0169WRN_UnreferencedField() { var text = @" public class ClassX { int i; // CS0169, i is not used anywhere public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,8): warning CS0169: The field 'ClassX.i' is never used // int i; // CS0169, i is not used anywhere Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("ClassX.i") ); } [Fact] public void CS0169WRN_UnreferencedField02() { var text = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""OtherAssembly"")] internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (8,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (14,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0169WRN_UnreferencedField03() { var text = @"internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0649: Field 'InternalClass.ActuallyInternal' is never assigned to, and will always have its default value 0 // internal int ActuallyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ActuallyInternal").WithArguments("InternalClass.ActuallyInternal", "0"), // (5,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (6,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (7,16): warning CS0649: Field 'InternalClass.EffectivelyInternal' is never assigned to, and will always have its default value 0 // public int EffectivelyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyInternal").WithArguments("InternalClass.EffectivelyInternal", "0"), // (12,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0183WRN_IsAlwaysTrue() { var text = @"using System; public class IsTest10 { public static int Main(String[] args) { Object obj3 = null; String str2 = ""Is 'is' too strict, per error CS0183?""; obj3 = str2; if (str2 is Object) // no error CS0183 Console.WriteLine(""str2 is Object""); Int32 int2 = 1; if (int2 is Object) // error CS0183 Console.WriteLine(""int2 is Object""); return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_IsAlwaysTrue, Line = 14, Column = 13, IsWarning = true }); // TODO: extra checking } // Note: CS0184 tests moved to CodeGenOperator.cs to include IL verification. [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField() { var text = @" class X : System.MarshalByRefObject { public int i; } class M { public int i; static void AddSeventeen(ref int i) { i += 17; } static void Main() { X x = new X(); x.i = 12; AddSeventeen(ref x.i); // CS0197 // OK M m = new M(); m.i = 12; AddSeventeen(ref m.i); } } "; CreateCompilation(text).VerifyDiagnostics( // (19,24): warning CS0197: Passing 'X.i' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // AddSeventeen(ref x.i); // CS0197 Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "x.i").WithArguments("X.i")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_RefKind() { var text = @" class NotByRef { public int Instance; public static int Static; } class ByRef : System.MarshalByRefObject { public int Instance; public static int Static; } class Test { void M(ByRef b, NotByRef n) { None(n.Instance); Out(out n.Instance); Ref(ref n.Instance); None(NotByRef.Static); Out(out NotByRef.Static); Ref(ref NotByRef.Static); None(b.Instance); Out(out b.Instance); Ref(ref b.Instance); None(ByRef.Static); Out(out ByRef.Static); Ref(ref ByRef.Static); } void None(int x) { throw null; } void Out(out int x) { throw null; } void Ref(ref int x) { throw null; } } "; CreateCompilation(text).VerifyDiagnostics( // (27,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Out(out b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance"), // (28,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_Receiver() { var text = @" using System; class ByRef : MarshalByRefObject { public int F; protected void Ref(ref int x) { } void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); } } class Derived : ByRef { void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); Ref(ref base.F); //Ref(ref ((ByRef)base).F); } } "; CreateCompilation(text).VerifyDiagnostics( // (15,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F"), // (26,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F")); } [Fact] public void CS0219WRN_UnreferencedVarAssg01() { var text = @"public class MyClass { public static void Main() { int a = 0; // CS0219 } }"; CreateCompilation(text).VerifyDiagnostics( // (5,13): warning CS0219: The variable 'a' is assigned but its value is never used // int a = 0; // CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a") ); } [Fact] public void CS0219WRN_UnreferencedVarAssg02() { var text = @" public class clx { static void Main(string[] args) { int x = 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13)); } [Fact] public void CS0219WRN_UnreferencedVarAssg03() { var text = @" public class clx { static void Main(string[] args) { int? x; x = null; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 14)); } [Fact, WorkItem(542473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542473"), WorkItem(542474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542474")] public void CS0219WRN_UnreferencedVarAssg_StructString() { var text = @" class program { static void Main(string[] args) { s1 y = new s1(); string s = """"; } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (6,12): warning CS0219: The variable 'y' is assigned but its value is never used // s1 y = new s1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 12), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(7, 16) ); } [Fact, WorkItem(542494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542494")] public void CS0219WRN_UnreferencedVarAssg_Default() { var text = @" class S { public int x = 5; } class C { public static void Main() { var x = default(S); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = default(S); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 13) ); } [Fact] public void CS0219WRN_UnreferencedVarAssg_For() { var text = @" class C { public static void Main() { for (int i = 1; ; ) { break; } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0219: The variable 'i' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 18) ); } [Fact, WorkItem(546619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546619")] public void NoCS0219WRN_UnreferencedVarAssg_ObjectInitializer() { var text = @" struct S { public int X { set {} } } class C { public static void Main() { S s = new S { X = 2 }; // no error - not a constant int? i = new int? { }; // ditto - not the default value (though bitwise equal to it) } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542472")] public void CS0251WRN_NegativeArrayIndex() { var text = @" class C { static void Main() { int[] a = new int[1]; int[,] b = new int[1, 1]; a[-1] = 1; // CS0251 a[-1, -1] = 1; // Dev10 reports CS0022 and CS0251 (twice), Roslyn reports CS0022 b[-1] = 1; // CS0022 b[-1, -1] = 1; // fine } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0251: Indexing an array with a negative index (array indices always start at zero) Diagnostic(ErrorCode.WRN_NegativeArrayIndex, "-1"), // (9,9): error CS0022: Wrong number of indices inside []; expected '1' Diagnostic(ErrorCode.ERR_BadIndexCount, "a[-1, -1]").WithArguments("1"), // (10,9): error CS0022: Wrong number of indices inside []; expected '2' Diagnostic(ErrorCode.ERR_BadIndexCount, "b[-1]").WithArguments("2")); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0252WRN_BadRefCompareLeft() { var text = @"class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool b = o == s; // CS0252 } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; // CS0252 Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string") ); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_02() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { MethodSymbol a1 = null; MethodSymbol a2 = new MethodSymbol(); // In these cases the programmer explicitly inserted a cast to use object equality instead // of the user-defined equality operator. Since the programmer did this explicitly, in // Roslyn we suppress the diagnostic that was given by the native compiler suggesting casting // the object-typed operand back to type Symbol to get value equality. Console.WriteLine((object)a1 == a2); Console.WriteLine((object)a1 != a2); Console.WriteLine((object)a2 == a1); Console.WriteLine((object)a2 != a1); Console.WriteLine(a1 == (object)a2); Console.WriteLine(a1 != (object)a2); Console.WriteLine(a2 == (object)a1); Console.WriteLine(a2 != (object)a1); } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_03() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { Object a1 = null; MethodSymbol a2 = new MethodSymbol(); Console.WriteLine(a1 == a2); Console.WriteLine(a1 != a2); Console.WriteLine(a2 == a1); Console.WriteLine(a2 != a1); } }"; CreateCompilation(text).VerifyDiagnostics( // (34,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 == a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 == a2").WithArguments("Symbol"), // (35,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 != a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 != a2").WithArguments("Symbol"), // (36,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 == a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 == a1").WithArguments("Symbol"), // (37,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 != a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 != a1").WithArguments("Symbol") ); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0253WRN_BadRefCompareRight() { var text = @" class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool c = s == o; // CS0253 // try the following line instead // bool c = s == (string)o; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,16): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string' // bool c = s == o; // CS0253 Diagnostic(ErrorCode.WRN_BadRefCompareRight, "s == o").WithArguments("string") ); } [WorkItem(730177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730177")] [Fact] public void CS0253WRN_BadRefCompare_None() { var text = @"using System; class MyClass { public static void Main() { MulticastDelegate x1 = null; bool b1 = x1 == null; bool b2 = x1 != null; bool b3 = null == x1; bool b4 = null != x1; } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(542399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542399")] [Fact] public void CS0278WRN_PatternIsAmbiguous01() { var text = @" using System.Collections.Generic; public class myTest { public static void TestForeach<W>(W w) where W: IEnumerable<int>, IEnumerable<string> { foreach (int i in w) {} // CS0278 } } "; CreateCompilation(text).VerifyDiagnostics( // (8,25): warning CS0278: 'W' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()'. // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "w").WithArguments("W", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), // (8,25): error CS1640: foreach statement cannot operate on variables of type 'W' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "w").WithArguments("W", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS0278WRN_PatternIsAmbiguous02() { var text = @"using System.Collections; using System.Collections.Generic; class A : IEnumerable<A> { public IEnumerator<A> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : IEnumerable<B> { IEnumerator<B> IEnumerable<B>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C : IEnumerable<C>, IEnumerable<string> { public IEnumerator<C> GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class D : IEnumerable<D>, IEnumerable<string> { IEnumerator<D> IEnumerable<D>.GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class E { static void M<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) where T1 : A, IEnumerable<A> // duplicate interfaces where T2 : B, IEnumerable<B> // duplicate interfaces where T3 : A, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T4 : B, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T5 : C, IEnumerable<int> // multiple interfaces where T6 : D, IEnumerable<int> // multiple interfaces where T7 : A, IEnumerable<string>, IEnumerable<A> // duplicate and multiple interfaces where T8 : B, IEnumerable<string>, IEnumerable<B> // duplicate and multiple interfaces where T9 : C, IEnumerable<C> // duplicate and multiple interfaces where T10 : D, IEnumerable<D> // duplicate and multiple interfaces { foreach (A o in t1) { } foreach (B o in t2) { } foreach (A o in t3) { } foreach (var o in t4) { } foreach (C o in t5) { } foreach (int o in t6) { } foreach (A o in t7) { } foreach (var o in t8) { } foreach (C o in t9) { } foreach (D o in t10) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (42,27): warning CS0278: 'T4' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t4").WithArguments("T4", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()").WithLocation(42, 27), // (42,27): error CS1640: foreach statement cannot operate on variables of type 'T4' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t4").WithArguments("T4", "System.Collections.Generic.IEnumerable<T>").WithLocation(42, 27), // (46,27): warning CS0278: 'T8' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<B>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t8").WithArguments("T8", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<B>.GetEnumerator()").WithLocation(46, 27), // (46,27): error CS1640: foreach statement cannot operate on variables of type 'T8' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t8").WithArguments("T8", "System.Collections.Generic.IEnumerable<T>").WithLocation(46, 27)); } [Fact] public void CS0279WRN_PatternStaticOrInaccessible() { var text = @" using System.Collections; public class myTest : IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } public static void Main() { foreach (int i in new myTest()) {} // CS0279 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,27): warning CS0279: 'myTest' does not implement the 'collection' pattern. 'myTest.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new myTest()").WithArguments("myTest", "collection", "myTest.GetEnumerator()")); } [Fact] public void CS0280WRN_PatternBadSignature() { var text = @" using System.Collections; public class ValidBase: IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } } class Derived : ValidBase { // field, not method new public int GetEnumerator; } public class Test { public static void Main() { foreach (int i in new Derived()) {} // CS0280 } } "; CreateCompilation(text).VerifyDiagnostics( // (27,25): warning CS0280: 'Derived' does not implement the 'collection' pattern. 'Derived.GetEnumerator' has the wrong signature. // foreach (int i in new Derived()) {} // CS0280 Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Derived()").WithArguments("Derived", "collection", "Derived.GetEnumerator"), // (20,19): warning CS0649: Field 'Derived.GetEnumerator' is never assigned to, and will always have its default value 0 // new public int GetEnumerator; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "GetEnumerator").WithArguments("Derived.GetEnumerator", "0") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg() { var text = @" class C { private int i = 1; // CS0414 public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,16): warning CS0414: The field 'C.i' is assigned but its value is never used // private int i = 1; // CS0414 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("C.i") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg02() { var text = @"class S<T1, T2> { T1 t1_field = default(T1); }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,8): warning CS0414: The field 'S<T1, T2>.t1_field' is assigned but its value is never used // T1 t1_field = default(T1); Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "t1_field").WithArguments("S<T1, T2>.t1_field").WithLocation(3, 8) ); } [Fact] public void CS0419WRN_AmbiguousXMLReference() { var text = @" interface I { void F(); void F(int i); } public class MyClass { /// <see cref=""I.F""/> public static void MyMethod(int i) { } public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,14): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass' // public class MyClass Diagnostic(ErrorCode.WRN_MissingXMLComment, "MyClass").WithArguments("MyClass"), // (9,19): warning CS0419: Ambiguous reference in cref attribute: 'I.F'. Assuming 'I.F()', but could have also matched other overloads including 'I.F(int)'. // /// <see cref="I.F"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "I.F").WithArguments("I.F", "I.F()", "I.F(int)"), // (13,23): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("MyClass.Main()")); } [Fact] public void CS0420WRN_VolatileByRef() { var text = @" class TestClass { private volatile int i; public void TestVolatileRef(ref int ii) { } public void TestVolatileOut(out int ii) { ii = 0; } public static void Main() { TestClass x = new TestClass(); x.TestVolatileRef(ref x.i); // CS0420 x.TestVolatileOut(out x.i); // CS0420 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i"), // (19,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i")); } [Fact] public void CS0420WRN_VolatileByRef_Suppressed() { var text = @" using System.Threading; class TestClass { private static volatile int x = 0; public static void TestVolatileByRef() { Interlocked.Increment(ref x); // no CS0420 Interlocked.Decrement(ref x); // no CS0420 Interlocked.Add(ref x, 0); // no CS0420 Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 Interlocked.Exchange(ref x, 0); // no CS0420 // using fully qualified name System.Threading.Interlocked.Increment(ref x); // no CS0420 System.Threading.Interlocked.Decrement(ref x); // no CS0420 System.Threading.Interlocked.Add(ref x, 0); // no CS0420 System.Threading.Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 System.Threading.Interlocked.Exchange(ref x, 0); // no CS0420 // passing volatile variables in a nested way Interlocked.Increment(ref Method1(ref x).y); // CS0420 for x Interlocked.Decrement(ref Method1(ref x).y); // CS0420 for x Interlocked.Add(ref Method1(ref x).y, 0); // CS0420 for x Interlocked.CompareExchange(ref Method1(ref x).y, 0, 0); // CS0420 for x Interlocked.Exchange(ref Method1(ref x).y, 0); // CS0420 for x // located as a function argument goo(Interlocked.Increment(ref x)); // no CS0420 } public static int goo(int x) { return x; } public static MyClass Method1(ref int x) { return new MyClass(); } public class MyClass { public volatile int y = 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (24,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (25,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (26,39): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (27,51): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (28,44): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x")); } [WorkItem(728380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728380")] [Fact] public void Repro728380() { var source = @" class Test { static volatile int x; unsafe static void goo(int* pX) { } static int Main() { unsafe { Test.goo(&x); } return 1; } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,27): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.ERR_FixedNeeded, "&x"), // (9,28): warning CS0420: 'Test.x': a reference to a volatile field will not be treated as volatile // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("Test.x")); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275")] public void CS0429WRN_UnreachableExpr() { var text = @" public class cs0429 { public static void Main() { if (false && myTest()) // CS0429 // Try the following line instead: // if (true && myTest()) { } else { int i = 0; i++; } } static bool myTest() { return true; } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275"), WorkItem(530071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530071")] public void CS0429WRN_UnreachableExpr_02() { var text = @" class Program { static bool b = true; const bool con = true; static void Main(string[] args) { int x = 1; int y = 1; int s = true ? x++ : y++; // y++ unreachable s = x == y ? x++ : y++; // OK s = con ? x++ : y++; // y++ unreachable bool con1 = true; s = con1 ? x++ : y++; // OK s = b ? x++ : y++; s = 1 < 2 ? x++ : y++; // y++ unreachable } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(543943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543943")] public void CS0458WRN_AlwaysNull() { var text = @" public class Test { public static void Main() { int? x = 0; x = null + x; x = x + default(int?); x += new int?(); x = null - x; x = x - default(int?); x -= new int?(); x = null * x; x = x * default(int?); x *= new int?(); x = null / x; x = x / default(int?); x /= new int?(); x = null % x; x = x % default(int?); x %= new int?(); x = null << x; x = x << default(int?); x <<= new int?(); x = null >> x; x = x >> default(int?); x >>= new int?(); x = null & x; x = x & default(int?); x &= new int?(); x = null | x; x = x | default(int?); x |= new int?(); x = null ^ x; x = x ^ default(int?); x ^= new int?(); //The below block of code should not raise a warning bool? y = null; y = y & null; y = y |false; y = true | null; double? d = +default(double?); int? i = -default(int?); long? l = ~default(long?); bool? b = !default(bool?); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AlwaysNull, "null + x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x + default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x += new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null - x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x - default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x -= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null * x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x * default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x *= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null / x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x / default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x /= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null % x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x % default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x %= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null << x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x << default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x <<= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null >> x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >> default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >>= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null & x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x & default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x &= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null | x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x | default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x |= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null ^ x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^ default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "+default(double?)").WithArguments("double?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "-default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "~default(long?)").WithArguments("long?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "!default(bool?)").WithArguments("bool?") ); } [Fact] public void CS0464WRN_CmpAlwaysFalse() { var text = @" class MyClass { public struct S { public static bool operator <(S x, S y) { return true; } public static bool operator >(S x, S y) { return true; } public static bool operator <=(S x, S y) { return true; } public static bool operator >=(S x, S y) { return true; } } public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } public static void Main() { S s = default(S); S? t = s; int i = 0; int? n = i; W(i < null); // CS0464 W(i <= null); // CS0464 W(i > null); // CS0464 W(i >= null); // CS0464 W(n < null); // CS0464 W(n <= null); // CS0464 W(n > null); // CS0464 W(n >= null); // CS0464 W(s < null); // CS0464 W(s <= null); // CS0464 W(s > null); // CS0464 W(s >= null); // CS0464 W(t < null); // CS0464 W(t <= null); // CS0464 W(t > null); // CS0464 W(t >= null); // CS0464 W(i < default(short?)); // CS0464 W(i <= default(short?)); // CS0464 W(i > default(short?)); // CS0464 W(i >= default(short?)); // CS0464 W(n < default(short?)); // CS0464 W(n <= default(short?)); // CS0464 W(n > default(short?)); // CS0464 W(n >= default(short?)); // CS0464 W(s < default(S?)); // CS0464 W(s <= default(S?)); // CS0464 W(s > default(S?)); // CS0464 W(s >= default(S?)); // CS0464 W(t < default(S?)); // CS0464 W(t <= default(S?)); // CS0464 W(t > default(S?)); // CS0464 W(t >= default(S?)); // CS0464 W(i < new sbyte?()); // CS0464 W(i <= new sbyte?()); // CS0464 W(i > new sbyte?()); // CS0464 W(i >= new sbyte?()); // CS0464 W(n < new sbyte?()); // CS0464 W(n <= new sbyte?()); // CS0464 W(n > new sbyte?()); // CS0464 W(n >= new sbyte?()); // CS0464 W(s < new S?()); // CS0464 W(s <= new S?()); // CS0464 W(s > new S?()); // CS0464 W(s >= new S?()); // CS0464 W(t < new S?()); // CS0464 W(t <= new S?()); // CS0464 W(t > new S?()); // CS0464 W(t >= new S?()); // CS0464 System.Console.WriteLine(); W(null < i); // CS0464 W(null <= i); // CS0464 W(null > i); // CS0464 W(null >= i); // CS0464 W(null < n); // CS0464 W(null <= n); // CS0464 W(null > n); // CS0464 W(null >= n); // CS0464 W(null < s); // CS0464 W(null <= s); // CS0464 W(null > s); // CS0464 W(null >= s); // CS0464 W(null < t); // CS0464 W(null <= t); // CS0464 W(null > t); // CS0464 W(null >= t); // CS0464 W(default(short?) < i); // CS0464 W(default(short?) <= i); // CS0464 W(default(short?) > i); // CS0464 W(default(short?) >= i); // CS0464 W(default(short?) < n); // CS0464 W(default(short?) <= n); // CS0464 W(default(short?) > n); // CS0464 W(default(short?) >= n); // CS0464 W(default(S?) < s); // CS0464 W(default(S?) <= s); // CS0464 W(default(S?) > s); // CS0464 W(default(S?) >= s); // CS0464 W(default(S?) < t); // CS0464 W(default(S?) <= t); // CS0464 W(default(S?) > t); // CS0464 W(default(S?) >= t); // CS0464 W(new sbyte?() < i); // CS0464 W(new sbyte?() <= i); // CS0464 W(new sbyte?() > i); // CS0464 W(new sbyte?() >= i); // CS0464 W(new sbyte?() < n); // CS0464 W(new sbyte?() <= n); // CS0464 W(new sbyte?() > n); // CS0464 W(new sbyte?() > n); // CS0464 W(new S?() < s); // CS0464 W(new S?() <= s); // CS0464 W(new S?() > s); // CS0464 W(new S?() >= s); // CS0464 W(new S?() < t); // CS0464 W(new S?() <= t); // CS0464 W(new S?() > t); // CS0464 W(new S?() > t); // CS0464 System.Console.WriteLine(); W(null > null); // CS0464 W(null >= null); // CS0464 W(null < null); // CS0464 W(null <= null); // CS0464 } } "; var verifier = CompileAndVerify(source: text, expectedOutput: @"ffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffff ffff"); CreateCompilation(text).VerifyDiagnostics( // (25,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < null").WithArguments("int?"), // (26,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= null").WithArguments("int?"), // (27,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > null").WithArguments("int?"), // (28,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= null").WithArguments("int?"), // (30,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < null").WithArguments("int?"), // (31,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= null").WithArguments("int?"), // (32,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > null").WithArguments("int?"), // (33,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= null").WithArguments("int?"), // (35,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < null").WithArguments("MyClass.S?"), // (36,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= null").WithArguments("MyClass.S?"), // (37,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > null").WithArguments("MyClass.S?"), // (38,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= null").WithArguments("MyClass.S?"), // (40,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < null").WithArguments("MyClass.S?"), // (41,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= null").WithArguments("MyClass.S?"), // (42,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > null").WithArguments("MyClass.S?"), // (43,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= null").WithArguments("MyClass.S?"), // (45,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < default(short?)").WithArguments("short?"), // (46,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= default(short?)").WithArguments("short?"), // (47,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > default(short?)").WithArguments("short?"), // (48,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= default(short?)").WithArguments("short?"), // (50,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < default(short?)").WithArguments("short?"), // (51,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= default(short?)").WithArguments("short?"), // (52,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > default(short?)").WithArguments("short?"), // (53,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= default(short?)").WithArguments("short?"), // (55,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < default(S?)").WithArguments("MyClass.S?"), // (56,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= default(S?)").WithArguments("MyClass.S?"), // (57,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > default(S?)").WithArguments("MyClass.S?"), // (58,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= default(S?)").WithArguments("MyClass.S?"), // (60,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < default(S?)").WithArguments("MyClass.S?"), // (61,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= default(S?)").WithArguments("MyClass.S?"), // (62,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > default(S?)").WithArguments("MyClass.S?"), // (63,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= default(S?)").WithArguments("MyClass.S?"), // (65,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < new sbyte?()").WithArguments("sbyte?"), // (66,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= new sbyte?()").WithArguments("sbyte?"), // (67,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > new sbyte?()").WithArguments("sbyte?"), // (68,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= new sbyte?()").WithArguments("sbyte?"), // (70,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < new sbyte?()").WithArguments("sbyte?"), // (71,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= new sbyte?()").WithArguments("sbyte?"), // (72,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > new sbyte?()").WithArguments("sbyte?"), // (73,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= new sbyte?()").WithArguments("sbyte?"), // (75,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < new S?()").WithArguments("MyClass.S?"), // (76,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= new S?()").WithArguments("MyClass.S?"), // (77,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > new S?()").WithArguments("MyClass.S?"), // (78,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= new S?()").WithArguments("MyClass.S?"), // (80,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < new S?()").WithArguments("MyClass.S?"), // (81,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= new S?()").WithArguments("MyClass.S?"), // (82,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > new S?()").WithArguments("MyClass.S?"), // (83,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= new S?()").WithArguments("MyClass.S?"), // (87,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < i").WithArguments("int?"), // (88,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= i").WithArguments("int?"), // (89,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > i").WithArguments("int?"), // (90,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= i").WithArguments("int?"), // (92,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < n").WithArguments("int?"), // (93,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= n").WithArguments("int?"), // (94,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > n").WithArguments("int?"), // (95,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= n").WithArguments("int?"), // (97,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < s").WithArguments("MyClass.S?"), // (98,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= s").WithArguments("MyClass.S?"), // (99,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > s").WithArguments("MyClass.S?"), // (100,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= s").WithArguments("MyClass.S?"), // (102,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < t").WithArguments("MyClass.S?"), // (103,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= t").WithArguments("MyClass.S?"), // (104,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > t").WithArguments("MyClass.S?"), // (105,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= t").WithArguments("MyClass.S?"), // (107,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < i").WithArguments("short?"), // (108,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= i").WithArguments("short?"), // (109,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > i").WithArguments("short?"), // (110,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= i").WithArguments("short?"), // (112,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < n").WithArguments("short?"), // (113,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= n").WithArguments("short?"), // (114,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > n").WithArguments("short?"), // (115,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= n").WithArguments("short?"), // (117,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < s").WithArguments("MyClass.S?"), // (118,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= s").WithArguments("MyClass.S?"), // (119,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > s").WithArguments("MyClass.S?"), // (120,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= s").WithArguments("MyClass.S?"), // (122,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < t").WithArguments("MyClass.S?"), // (123,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= t").WithArguments("MyClass.S?"), // (124,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > t").WithArguments("MyClass.S?"), // (125,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= t").WithArguments("MyClass.S?"), // (127,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < i").WithArguments("sbyte?"), // (128,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= i").WithArguments("sbyte?"), // (129,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > i").WithArguments("sbyte?"), // (130,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() >= i").WithArguments("sbyte?"), // (132,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < n").WithArguments("sbyte?"), // (133,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= n").WithArguments("sbyte?"), // (134,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (135,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (137,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < s").WithArguments("MyClass.S?"), // (138,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= s").WithArguments("MyClass.S?"), // (139,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > s").WithArguments("MyClass.S?"), // (140,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() >= s").WithArguments("MyClass.S?"), // (142,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < t").WithArguments("MyClass.S?"), // (143,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= t").WithArguments("MyClass.S?"), // (144,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (145,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (149,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > null").WithArguments("int?"), // (150,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= null").WithArguments("int?"), // (151,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < null").WithArguments("int?"), // (152,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= null").WithArguments("int?") ); } [Fact] public void CS0469WRN_GotoCaseShouldConvert() { var text = @" class Test { static void Main() { char c = (char)180; switch (c) { case (char)127: break; case (char)180: goto case 127; // CS0469 // try the following line instead // goto case (char) 127; } } } "; CreateCompilation(text).VerifyDiagnostics( // (13,13): warning CS0469: The 'goto case' value is not implicitly convertible to type 'char' // goto case 127; // CS0469 Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 127;").WithArguments("char").WithLocation(13, 13) ); } [Fact, WorkItem(663, "https://github.com/dotnet/roslyn/issues/663")] public void CS0472WRN_NubExprIsConstBool() { // Due to a long-standing bug, the native compiler does not produce warnings for "guid == null", // but does for "int == null". Roslyn corrects this lapse and produces warnings for both built-in // and user-defined lifted equality operators, but the new warnings for user-defined types are // only given with /warn:n where n >= 5. var text = @" using System; class MyClass { public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } enum E : int { }; public static void Main() { Guid g = default(Guid); Guid? h = g; int i = 0; int? n = i; W(i == null); // CS0472 W(i != null); // CS0472 W(n == null); // no error W(n != null); // no error W(g == null); // CS0472 W(g != null); // CS0472 W(h == null); // no error W(h != null); // no error W(i == default(short?)); // CS0472 W(i != default(short?)); // CS0472 W(n == default(short?)); // no error W(n != default(short?)); // no error W(g == default(Guid?)); // CS0472 W(g != default(Guid?)); // CS0472 W(h == default(Guid?)); // no error W(h != default(Guid?)); // no error W(i == new sbyte?()); // CS0472 W(i != new sbyte?()); // CS0472 W(n == new sbyte?()); // no error W(n != new sbyte?()); // no error W(g == new Guid?()); // CS0472 W(g != new Guid?()); // CS0472 W(h == new Guid?()); // no error W(h != new Guid?()); // no error System.Console.WriteLine(); W(null == i); // CS0472 W(null != i); // CS0472 W(null == n); // no error W(null != n); // no error W(null == g); // CS0472 W(null != g); // CS0472 W(null == h); // no error W(null != h); // no error W(default(long?) == i); // CS0472 W(default(long?) != i); // CS0472 W(default(long?) == n); // no error W(default(long?) != n); // no error W(default(Guid?) == g); // CS0472 W(default(Guid?) != g); // CS0472 W(default(Guid?) == h); // no error W(default(Guid?) != h); // no error W(new double?() == i); // CS0472 W(new double?() != i); // CS0472 W(new double?() == n); // no error W(new double?() != n); // no error W(new Guid?() == g); // CS0472 W(new Guid?() != g); // CS0472 W(new Guid?() == h); // no error W(new Guid?() != h); // no error System.Console.WriteLine(); W(null == null); // No error, because both sides are nullable, but of course W(null != null); // we could give a warning here as well. System.Console.WriteLine(); //check comparisons with converted constants W((E?)1 == null); W(null != (E?)1); W((int?)1 == null); W(null != (int?)1); //check comparisons when null is converted W(0 == (int?)null); W((int?)null != 0); W(0 == (E?)null); W((E?)null != 0); } } "; string expected = @"ftftftftftftftftftftftft ftftftftftftftftftftftft tf ftftftft"; var fullExpected = new DiagnosticDescription[] { // (19,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(19, 11), // (20,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?").WithLocation(20, 11), // (23,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == null").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(23, 11), // (24,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != null").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(24, 11), // (28,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i == default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == default(short?)").WithArguments("false", "int", "short?").WithLocation(28, 11), // (29,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i != default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != default(short?)").WithArguments("true", "int", "short?").WithLocation(29, 11), // (32,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == default(Guid?)").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(32, 11), // (33,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != default(Guid?)").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(33, 11), // (37,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i == new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == new sbyte?()").WithArguments("false", "int", "sbyte?").WithLocation(37, 11), // (38,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i != new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != new sbyte?()").WithArguments("true", "int", "sbyte?").WithLocation(38, 11), // (41,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == new Guid?()").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(41, 11), // (42,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != new Guid?()").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(42, 11), // (49,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null == i").WithArguments("false", "int", "int?").WithLocation(49, 11), // (50,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?").WithLocation(50, 11), // (53,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(53, 11), // (54,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(54, 11), // (58,11): warning CS0472: The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) == i").WithArguments("false", "long", "long?").WithLocation(58, 11), // (59,11): warning CS0472: The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) != i").WithArguments("true", "long", "long?").WithLocation(59, 11), // (62,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(62, 11), // (63,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(63, 11), // (67,11): warning CS0472: The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() == i").WithArguments("false", "double", "double?").WithLocation(67, 11), // (68,11): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() != i").WithArguments("true", "double", "double?").WithLocation(68, 11), // (71,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(71, 11), // (72,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(72, 11), // (84,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)1 == null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(84, 11), // (85,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(null != (E?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (E?)1").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(85, 11), // (87,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)1 == null").WithArguments("false", "int", "int?").WithLocation(87, 11), // (88,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != (int?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (int?)1").WithArguments("true", "int", "int?").WithLocation(88, 11), // (92,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(0 == (int?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (int?)null").WithArguments("false", "int", "int?").WithLocation(92, 11), // (93,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)null != 0").WithArguments("true", "int", "int?").WithLocation(93, 11), // (95,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(0 == (E?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (E?)null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(95, 11), // (96,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)null != 0").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(96, 11) }; var compatibleExpected = fullExpected.Where(d => !d.Code.Equals((int)ErrorCode.WRN_NubExprIsConstBool2)).ToArray(); this.CompileAndVerify(source: text, expectedOutput: expected, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(compatibleExpected); this.CompileAndVerify(source: text, expectedOutput: expected).VerifyDiagnostics(fullExpected); } [Fact] public void CS0472WRN_NubExprIsConstBool_ConstructorInitializer() { var text = @"class A { internal A(bool b) { } } class B : A { B(int i) : base(i == null) { } }"; CreateCompilation(text).VerifyDiagnostics( // (9,21): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // B(int i) : base(i == null) Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(9, 21)); } [Fact] public void CS0612WRN_DeprecatedSymbol() { var text = @" using System; class MyClass { [Obsolete] public static void ObsoleteMethod() { } [Obsolete] public static int ObsoleteField; } class MainClass { static public void Main() { MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated } } "; CreateCompilation(text). VerifyDiagnostics( // (17,7): warning CS0612: 'MyClass.ObsoleteMethod()' is obsolete // MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteMethod()").WithArguments("MyClass.ObsoleteMethod()"), // (18,7): warning CS0612: 'MyClass.ObsoleteField' is obsolete // MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteField").WithArguments("MyClass.ObsoleteField")); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0618WRN_DeprecatedSymbol() { var text = @" public class ConsoleStub { public static void Main(string[] args) { System.Collections.CaseInsensitiveHashCodeProvider x; System.Console.WriteLine(x); } }"; CreateCompilation(text). VerifyDiagnostics( // (6,9): warning CS0618: 'System.Collections.CaseInsensitiveHashCodeProvider' is obsolete: 'Please use StringComparer instead.' // System.Collections.CaseInsensitiveHashCodeProvider x; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Collections.CaseInsensitiveHashCodeProvider").WithArguments("System.Collections.CaseInsensitiveHashCodeProvider", "Please use StringComparer instead."), // (7,34): error CS0165: Use of unassigned local variable 'x' // System.Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x")); } [WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] [Fact] public void CS0649WRN_UnassignedInternalField() { var text = @" using System.Collections; class MyClass { Hashtable table; // CS0649 public void Func(object o, string p) { table[p] = o; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): warning CS0649: Field 'MyClass.table' is never assigned to, and will always have its default value null // Hashtable table; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "table").WithArguments("MyClass.table", "null") ); } [Fact, WorkItem(543454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543454")] public void CS0649WRN_UnassignedInternalField_1() { var text = @" public class GenClass<T, U> { } public class Outer { internal protected class C1 { } public class C2 { } internal class Test { public GenClass<C1, C2> Fld; } public static int Main() { return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld").WithArguments("Outer.Test.Fld", "null")); } [WorkItem(546449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546449")] [WorkItem(546949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546949")] [Fact] public void CS0652WRN_VacuousIntegralComp() { var text = @" public class Class1 { private static byte i = 0; public static void Main() { const short j = 256; if (i == j) // CS0652, 256 is out of range for byte i = 0; // However, we do not give this warning if both sides of the comparison are constants. In those // cases, we are probably in machine-generated code anyways. const byte k = 0; if (k == j) {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0652: Comparison to integral constant is useless; the constant is outside the range of type 'byte' // if (i == j) // CS0652, 256 is out of range for byte Diagnostic(ErrorCode.WRN_VacuousIntegralComp, "i == j").WithArguments("byte")); } [WorkItem(546790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546790")] [Fact] public void CS0652WRN_VacuousIntegralComp_ExplicitCast() { var text = @" using System; public class Program { public static void Main() { Int16 wSuiteMask = 0; const int VER_SUITE_WH_SERVER = 0x00008000; if (VER_SUITE_WH_SERVER == (Int32)wSuiteMask) { } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0665WRN_IncorrectBooleanAssg() { var text = @" class Test { public static void Main() { bool i = false; if (i = true) // CS0665 // try the following line instead // if (i == true) { } System.Console.WriteLine(i); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "i = true")); } [Fact, WorkItem(540777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777")] public void CS0665WRN_IncorrectBooleanAssg_ConditionalOperator() { var text = @" class Program { static int Main(string[] args) { bool a = true; System.Console.WriteLine(a); return ((a = false) ? 50 : 100); // Warning } } "; CreateCompilation(text).VerifyDiagnostics( // (8,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "a = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Contexts() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if (b = false) { } while (b = false) { } do { } while (b = false); for (; b = false; ) { } System.Console.WriteLine((b = false) ? 1 : 2); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // while (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (10,23): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // do { } while (b = false); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (11,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // for (; b = false; ) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (12,35): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // System.Console.WriteLine((b = false) ? 1 : 2); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Nesting() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if ((b = false)) { } // parens - warn if (((b = false))) { } // more parens - warn if (M(b = false)) { } // call - do not warn if ((bool)(b = false)) { } // cast - do not warn if ((b = false) || (b = true)) { } // binary operator - do not warn B bb = new B(); if (bb = false) { } // implicit conversion - do not warn } static bool M(bool b) { return b; } } class B { public static implicit operator B(bool b) { return new B(); } public static bool operator true(B b) { return true; } public static bool operator false(B b) { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if ((b = false)) { } // parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,15): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (((b = false))) { } // more parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact, WorkItem(909, "https://github.com/dotnet/roslyn/issues/909")] public void CS0675WRN_BitwiseOrSignExtend() { var text = @" public class sign { public static void Main() { int i32_hi = 1; int i32_lo = 1; ulong u64 = 1; sbyte i08 = 1; short i16 = -1; object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 object v2 = (ulong)i32_hi | u64; // CS0675 object v3 = (ulong)i32_hi | (ulong)i32_lo; // No warning; the sign extension bits are the same on both sides. object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 object v5 = (int)i08 | (int)i32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v6 = (((ulong)i32_hi) << 32) | (uint) i32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v7 = 0x0000BEEFU | (uint)i16; object v8 = 0xFFFFBEEFU | (uint)i16; object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 // We should do the exact same logic for nullables. int? ni32_hi = 1; int? ni32_lo = 1; ulong? nu64 = 1; sbyte? ni08 = 1; short? ni16 = -1; object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 object v12 = (ulong?)ni32_hi | nu64; // CS0675 object v13 = (ulong?)ni32_hi | (ulong?)ni32_lo; // No warning; the sign extension bits are the same on both sides. object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 object v15 = (int?)ni08 | (int?)ni32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v16 = (((ulong?)ni32_hi) << 32) | (uint?) ni32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v17 = 0x0000BEEFU | (uint?)ni16; object v18 = 0xFFFFBEEFU | (uint?)ni16; object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 } } class Test { static void Main() { long bits = 0; for (int i = 0; i < 32; i++) { if (i % 2 == 0) { bits |= (1 << i); bits = bits | (1 << i); } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long)i32_hi) << 32) | i32_lo"), // (13,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v2 = (ulong)i32_hi | u64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)i32_hi | u64"), // (15,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)(uint)(ushort)i08 | (ulong)i32_lo"), // (21,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint)i16"), // (31,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long?)ni32_hi) << 32) | ni32_lo"), // (32,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v12 = (ulong?)ni32_hi | nu64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)ni32_hi | nu64"), // (34,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo"), // (40,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint?)ni16"), // (53,17): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits |= (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits |= (1 << i)").WithLocation(53, 17), // (54,24): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits = bits | (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits | (1 << i)").WithLocation(54, 24) ); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose01() { CreateCompilation(@" using System; public class ValidBase : IDisposable { public void Dispose() { } } public class Logger { public static void dummy() { ValidBase vb = null; using (vb) { vb = null; // CS0728 } vb = null; } public static void Main() { } }") .VerifyDiagnostics( // (15,13): warning CS0728: Possibly incorrect assignment to local 'vb' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "vb").WithArguments("vb")); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose02() { CreateCompilation( @"class D : System.IDisposable { public void Dispose() { } } class C { static void M() { D d = new D(); using (d) { N(ref d); } lock (d) { N(ref d); } } static void N(ref D d) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(12, 19), Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(16, 19)); } [WorkItem(543615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615"), WorkItem(546550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546550")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CS0811ERR_DebugFullNameTooLong() { var text = @" using System; using System.Collections.Generic; namespace TestNamespace { using VeryLong = List<List<List<List<List<List<List<List<List<List<List<List<List <List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>; // CS0811 class Test { static int Main() { VeryLong goo = null; Console.WriteLine(goo); return 1; } } } "; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.DebugExe); var exebits = new System.IO.MemoryStream(); var pdbbits = new System.IO.MemoryStream(); var result = compilation.Emit(exebits, pdbbits, options: TestOptions.NativePdbEmit); result.Diagnostics.Verify( // (12,20): warning CS0811: The fully qualified name for 'AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is too long for debug information. Compile without '/debug' option. // static int Main() Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, "Main").WithArguments("AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(12, 20)); } [Fact] public void CS1058WRN_UnreachableGeneralCatch() { var text = @"class C { static void M() { try { } catch (System.Exception) { } catch (System.IO.IOException) { } catch { } try { } catch (System.IO.IOException) { } catch (System.Exception) { } catch { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.IO.IOException").WithArguments("System.Exception").WithLocation(7, 16), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(8, 9), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(12, 9)); } // [Fact(Skip = "11486")] // public void CS1060WRN_UninitializedField() // { // var text = @" //namespace CS1060 //{ // public class U // { // public int i; // } // // public struct S // { // public U u; // } // public class Test // { // static void Main() // { // S s; // s.u.i = 5; // CS1060 // } // } //} //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_UninitializedField, Line = 18, Column = 13, IsWarning = true } }); // } // [Fact()] // public void CS1064ERR_DebugFullNameTooLong() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = 1064, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact] public void CS1570WRN_XMLParseError() { var text = @" namespace ns { // the following line generates CS1570 /// <summary> returns true if < 5 </summary> // try this instead // /// <summary> returns true if &lt;5 </summary> public class MyClass { public static void Main () { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (5,35): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, ""), // (5,35): warning CS1570: XML comment has badly formed XML -- '5' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, " ").WithArguments("5"), // (11,26): warning CS1591: Missing XML comment for publicly visible type or member 'ns.MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("ns.MyClass.Main()")); } [Fact] public void CS1571WRN_DuplicateParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>An initial.</param> /// <param name='Int1'>Used to indicate status.</param> // CS1571 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,15): warning CS1571: XML comment has a duplicate param tag for 'Int1' // /// <param name='Int1'>Used to indicate status.</param> // CS1571 Diagnostic(ErrorCode.WRN_DuplicateParamTag, "name='Int1'").WithArguments("Int1")); } [Fact] public void CS1572WRN_UnmatchedParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>Used to indicate status.</param> /// <param name='Char2'>???</param> // CS1572 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,21): warning CS1572: XML comment has a param tag for 'Char2', but there is no parameter by that name // /// <param name='Char2'>???</param> // CS1572 Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Char2").WithArguments("Char2")); } [Fact] public void CS1573WRN_MissingParamTag() { var text = @" /// <summary> </summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// enter a comment for Char1? public static void MyMethod(int Int1, char Char1) { } /// <summary> </summary> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,48): warning CS1573: Parameter 'Char1' has no matching param tag in the XML comment for 'MyClass.MyMethod(int, char)' (but other parameters do) // public static void MyMethod(int Int1, char Char1) Diagnostic(ErrorCode.WRN_MissingParamTag, "Char1").WithArguments("Char1", "MyClass.MyMethod(int, char)")); } [Fact] public void CS1574WRN_BadXMLRef() { var text = @" /// <see cref=""D""/> public class C { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,16): warning CS1574: XML comment has cref attribute 'D' that could not be resolved // /// <see cref="D"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "D").WithArguments("D")); } [Fact] public void CS1580WRN_BadXMLRefParamType() { var text = @" /// <seealso cref=""Test(i)""/> // CS1580 public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public void Test(int i) { } /// <summary>help text</summary> public void Test(char i) { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1580: Invalid type for parameter 'i' in XML comment cref attribute: 'Test(i)' // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "i").WithArguments("i", "Test(i)"), // (2,20): warning CS1574: XML comment has cref attribute 'Test(i)' that could not be resolved // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRef, "Test(i)").WithArguments("Test(i)")); } [Fact] public void CS1581WRN_BadXMLRefReturnType() { var text = @" /// <summary>help text</summary> public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public static explicit operator int(MyClass f) { return 0; } } /// <seealso cref=""MyClass.explicit operator intt(MyClass)""/> // CS1581 public class MyClass2 { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (15,20): warning CS1581: Invalid return type in XML comment cref attribute // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "intt").WithArguments("intt", "MyClass.explicit operator intt(MyClass)"), // (15,20): warning CS1574: XML comment has cref attribute 'MyClass.explicit operator intt(MyClass)' that could not be resolved // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRef, "MyClass.explicit operator intt(MyClass)").WithArguments("explicit operator intt(MyClass)")); } [Fact] public void CS1584WRN_BadXMLRefSyntax() { var text = @" /// public class MyClass1 { /// public static MyClass1 operator /(MyClass1 a1, MyClass1 a2) { return null; } /// <seealso cref=""MyClass1.operator@""/> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (10,24): warning CS1584: XML comment has syntactically incorrect cref attribute 'MyClass1.operator@' // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "MyClass1.operator").WithArguments("MyClass1.operator@"), // (10,41): warning CS1658: Overloadable operator expected. See also error CS1037. // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_ErrorOverride, "@").WithArguments("Overloadable operator expected", "1037"), // (10,41): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @ // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, "")); } [Fact] public void CS1587WRN_UnprocessedXMLComment() { var text = @" /// <summary>test</summary> // CS1587, tag not allowed on namespace namespace MySpace { class MyClass { public static void Main() { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void CS1589WRN_NoResolver() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; var c = CreateCompilation( new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) }, options: TestOptions.ReleaseDll.WithXmlReferenceResolver(null)); c.VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- References to XML documents are not supported. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "References to XML documents are not supported.")); } [Fact] public void CS1589WRN_FailedInclude() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- Unable to find the specified file. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "File not found.")); } [Fact] public void CS1590WRN_InvalidInclude() { var text = @" /// <include path='MyDocs/MyMembers[@name=""test""]/*' /> // CS1590 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include path='MyDocs/MyMembers[@name="test"]/*' /> // CS1590 Diagnostic(ErrorCode.WRN_InvalidInclude, @"<include path='MyDocs/MyMembers[@name=""test""]/*' />").WithArguments("Missing file attribute")); } [Fact] public void CS1591WRN_MissingXMLComment() { var text = @" /// text public class Test { // /// text public static void Main() // CS1591 { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'Test.Main()' // public static void Main() // CS1591 Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("Test.Main()")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/18610")] public void CS1592WRN_XMLParseIncludeError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("&"); var sourceTemplate = @" /// <include file='{0}' path='element'/> public class Test {{ }} "; var comp = CreateCompilationWithMscorlib40AndDocumentationComments(string.Format(sourceTemplate, xmlFile.Path)); using (new EnsureEnglishUICulture()) { comp.VerifyDiagnostics( // dcf98d2ac30a.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Data at the root level is invalid.")); } } [Fact] public void CS1658WRN_ErrorOverride() { var text = @" /// <seealso cref=""""/> public class Test { /// public static int Main() { return 0; } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1584: XML comment has syntactically incorrect cref attribute '' // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""), // (2,20): warning CS1658: Identifier expected. See also error CS1001. // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001")); } // TODO (tomat): Also fix AttributeTests.DllImport_AttributeRedefinition [Fact(Skip = "530377"), WorkItem(530377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530377"), WorkItem(685159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685159")] public void CS1685WRN_MultiplePredefTypes() { var text = @" public static class C { public static void Extension(this int X) {} }"; // include both mscorlib 4.0 and System.Core 3.5, both of which contain ExtensionAttribute // These libraries are not yet in our suite CreateEmptyCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MultiplePredefTypes, "")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField() { var text = @" using System; class WarningCS1690 : MarshalByRefObject { int i = 5; public static void Main() { WarningCS1690 e = new WarningCS1690(); e.i.ToString(); // CS1690 int i = e.i; i.ToString(); e.i = i; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_CallOnNonAgileField, Line = 11, Column = 9, IsWarning = true } }); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Variations() { var text = @" using System; struct S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (19,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event = null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (20,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event += null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (21,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Property++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (22,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s[0]++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (23,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.M(); Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (24,24): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // Action a = w.s.M; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Class() { var text = @" using System; class S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,11): warning CS0649: Field 'S.WarningCS1690.s' is never assigned to, and will always have its default value null // S s; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s").WithArguments("S.WarningCS1690.s", "null"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } // [Fact()] // public void CS1707WRN_DelegateNewMethBind() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_DelegateNewMethBind, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact(), WorkItem(530384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530384")] public void CS1709WRN_EmptyFileName() { var text = @" class Test { static void Main() { #pragma checksum """" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" """" // CS1709 } } "; //EDMAURER no longer giving this low-value warning. CreateCompilation(text). VerifyDiagnostics(); //VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptyFileName, @"""")); } [Fact] public void CS1710WRN_DuplicateTypeParamTag() { var text = @" class Stack<ItemType> { } /// <typeparam name=""MyType"">can be an int</typeparam> /// <typeparam name=""MyType"">can be an int</typeparam> class MyStackWrapper<MyType> { // Open constructed type Stack<MyType>. Stack<MyType> stack; public MyStackWrapper(Stack<MyType> s) { stack = s; } } class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,16): warning CS1710: XML comment has a duplicate typeparam tag for 'MyType' // /// <typeparam name="MyType">can be an int</typeparam> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""MyType""").WithArguments("MyType")); } [Fact] public void CS1711WRN_UnmatchedTypeParamTag() { var text = @" ///<typeparam name=""WrongName"">can be an int</typeparam> class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,21): warning CS1711: XML comment has a typeparam tag for 'WrongName', but there is no type parameter by that name // ///<typeparam name="WrongName">can be an int</typeparam> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "WrongName").WithArguments("WrongName")); } [Fact] public void CS1712WRN_MissingTypeParamTag() { var text = @" ///<summary>A generic list delegate.</summary> ///<typeparam name=""T"">The first type stored by the list.</typeparam> public delegate void List<T,W>(); /// public class Test { /// public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (4,29): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'List<T, W>' (but other type parameters do) // public delegate void List<T,W>(); Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "List<T, W>")); } [Fact] public void CS1717WRN_AssignmentToSelf() { var text = @" public class Test { public static void Main() { int x = 0; x = x; // CS1717 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_AssignmentToSelf, Line = 7, Column = 7, IsWarning = true } }); } [WorkItem(543470, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543470")] [Fact] public void CS1717WRN_AssignmentToSelf02() { var text = @" class C { void M(object p) { object oValue = p; if (oValue is int) { //(SQL 9.0) 653716 + common sense oValue = (double) ((int) oValue); } } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1717WRN_AssignmentToSelf03() { var text = @" using System; class Program { int f; event Action e; void Test(int p) { int l = 0; l = l; p = p; f = f; e = e; } } "; CreateCompilation(text).VerifyDiagnostics( // (13,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = l"), // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // p = p; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "p = p"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = f"), // (16,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = e")); } [Fact] public void CS1717WRN_AssignmentToSelf04() { var text = @" using System; class Program { int f; event Action e; static int sf; static event Action se; void Test(Program other) { f = this.f; e = this.e; f = other.f; //fine e = other.e; //fine sf = sf; se = se; sf = Program.sf; se = Program.se; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = this.f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = this.f"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = this.e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = this.e"), // (20,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = sf"), // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = se"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = Program.sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = Program.sf"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = Program.se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = Program.se")); } [Fact] public void CS1717WRN_AssignmentToSelf05() { var text = @" using System.Linq; class Program { static void Main(string[] args) { var unused = from x in args select x = x; } } "; // CONSIDER: dev11 reports WRN_AssignmentToSelf. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,44): error CS1947: Range variable 'x' cannot be assigned to -- it is read only // var unused = from x in args select x = x; Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "x").WithArguments("x")); } [Fact] public void CS1717WRN_AssignmentToSelf06() { var text = @" class C { void M( byte b, sbyte sb, short s, ushort us, int i, uint ui, long l, ulong ul, float f, double d, decimal m, bool bo, object o, C cl, S st) { b = (byte)b; sb = (sbyte)sb; s = (short)s; us = (ushort)us; i = (int)i; ui = (uint)ui; l = (long)l; ul = (ulong)ul; f = (float)f; // Not reported by dev11. d = (double)d; // Not reported by dev11. m = (decimal)m; bo = (bool)bo; o = (object)o; cl = (C)cl; st = (S)st; } } struct S { } "; // CONSIDER: dev11 does not strip off float or double identity-conversions and, thus, // does not warn about those assignments. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b = (byte)b; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b = (byte)b"), // (22,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sb = (sbyte)sb; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sb = (sbyte)sb"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // s = (short)s; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "s = (short)s"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // us = (ushort)us; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "us = (ushort)us"), // (25,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // i = (int)i; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "i = (int)i"), // (26,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ui = (uint)ui; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ui = (uint)ui"), // (27,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = (long)l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = (long)l"), // (28,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ul = (ulong)ul; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ul = (ulong)ul"), // (29,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = (float)f; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = (float)f"), // (30,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // d = (double)d; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "d = (double)d"), // (31,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // m = (decimal)m; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "m = (decimal)m"), // (32,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // bo = (bool)bo; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "bo = (bool)bo"), // (33,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // o = (object)o; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "o = (object)o"), // (34,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // cl = (C)cl; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "cl = (C)cl"), // (35,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // st = (S)st; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "st = (S)st")); } [Fact, WorkItem(546493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546493")] public void CS1718WRN_ComparisonToSelf() { var text = @" class Tester { static int j = 123; static void Main() { int i = 0; if (i == i) i++; if (j == Tester.j) j++; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (i == i) i++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i"), // (9,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (j == Tester.j) j++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "j == Tester.j")); } [Fact, WorkItem(580501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580501")] public void CS1718WRN_ComparisonToSelf2() { var text = @" using System.Linq; class Tester { static void Main() { var q = from int x1 in new[] { 2, 9, 1, 8, } where x1 > x1 // CS1718 select x1; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,15): warning CS1718: Comparison made to same variable; did you mean to compare something else? // where x1 > x1 // CS1718 Diagnostic(ErrorCode.WRN_ComparisonToSelf, "x1 > x1")); } [Fact] public void CS1720WRN_DotOnDefault01() { var source = @"class A { internal object P { get; set; } } interface I { object P { get; set; } } static class C { static void M<T1, T2, T3, T4, T5, T6, T7>() where T2 : new() where T3 : struct where T4 : class where T5 : T1 where T6 : A where T7 : I { default(int).GetHashCode(); default(object).GetHashCode(); default(T1).GetHashCode(); default(T2).GetHashCode(); default(T3).GetHashCode(); default(T4).GetHashCode(); default(T5).GetHashCode(); default(T6).GetHashCode(); default(T7).GetHashCode(); default(T6).P = null; default(T7).P = null; default(int).E(); default(object).E(); default(T1).E(); default(T2).E(); default(T3).E(); default(T4).E(); default(T5).E(); default(T6).E(); // Dev10 (incorrectly) reports CS1720 default(T7).E(); } static void E(this object o) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (20,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object' is null // default(object).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object).GetHashCode").WithArguments("object").WithLocation(20, 9), // (24,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null // default(T4).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4).GetHashCode").WithArguments("T4").WithLocation(24, 9), // (26,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).GetHashCode").WithArguments("T6").WithLocation(26, 9), // (28,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).P = null; Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).P").WithArguments("T6").WithLocation(28, 9)); CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, options: TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable)).VerifyDiagnostics( ); } [Fact] public void CS1720WRN_DotOnDefault02() { var source = @"class A { internal object this[object index] { get { return null; } set { } } } struct S { internal object this[object index] { get { return null; } set { } } } interface I { object this[object index] { get; set; } } class C { unsafe static void M<T1, T2, T3, T4>() where T1 : A where T2 : I where T3 : struct, I where T4 : class, I { object o; o = default(int*)[0]; o = default(A)[0]; o = default(S)[0]; o = default(I)[0]; o = default(object[])[0]; o = default(T1)[0]; o = default(T2)[0]; o = default(T3)[0]; o = default(T4)[0]; default(int*)[1] = 1; default(A)[1] = o; default(I)[1] = o; default(object[])[1] = o; default(T1)[1] = o; default(T2)[1] = o; default(T3)[1] = o; default(T4)[1] = o; } }"; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (23,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[0]").WithArguments("A").WithLocation(23, 13), // (25,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[0]").WithArguments("I").WithLocation(25, 13), // (26,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[0]").WithArguments("object[]").WithLocation(26, 13), // (27,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[0]").WithArguments("T1").WithLocation(27, 13), // (30,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[0]").WithArguments("T4").WithLocation(30, 13), // (32,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[1]").WithArguments("A").WithLocation(32, 9), // (33,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[1]").WithArguments("I").WithLocation(33, 9), // (34,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[1]").WithArguments("object[]").WithLocation(34, 9), // (35,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[1]").WithArguments("T1").WithLocation(35, 9), // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9), // Incorrect? See CS0131ERR_AssgLvalueExpected03 unit test. // (38,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[1]").WithArguments("T4").WithLocation(38, 9)); CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // default(T3)[1] = o; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9)); } [Fact] public void CS1720WRN_DotOnDefault03() { var source = @"static class A { static void Main() { System.Console.WriteLine(default(string).IsNull()); } internal static bool IsNull(this string val) { return (object)val == null; } } "; CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // Do not report the following warning: // (5,34): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null // System.Console.WriteLine(default(string).IsNull()); // Diagnostic(ErrorCode.WRN_DotOnDefault, "default(string).IsNull").WithArguments("string").WithLocation(5, 34) ); CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }).VerifyDiagnostics(); } [Fact] public void CS1723WRN_BadXMLRefTypeVar() { var text = @" ///<summary>A generic list class.</summary> ///<see cref=""T"" /> // CS1723 public class List<T> { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (3,15): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // ///<see cref="T" /> // CS1723 Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); } [Fact] public void CS1974WRN_DynamicDispatchToConditionalMethod() { var text = @" using System.Diagnostics; class Myclass { static void Main() { dynamic d = null; // Warning because Goo might be conditional. Goo(d); // No warning; only the two-parameter Bar is conditional. Bar(d); } [Conditional(""DEBUG"")] static void Goo(string d) {} [Conditional(""DEBUG"")] static void Bar(int x, int y) {} static void Bar(string x) {} }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (9,9): warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime because one or more applicable overloads are conditional methods. // Goo(d); Diagnostic(ErrorCode.WRN_DynamicDispatchToConditionalMethod, "Goo(d)").WithArguments("Goo")); } [Fact] public void CS1981WRN_IsDynamicIsConfusing() { var text = @" public class D : C { } public class C { public static int Main() { // is dynamic bool bi = 123 is dynamic; // dynamicType is valueType dynamic i2 = 123; bi = i2 is int; // dynamicType is refType dynamic c = new D(); bi = c is C; dynamic c2 = new C(); bi = c is C; // valueType as dynamic int i = 123 as dynamic; // refType as dynamic dynamic c3 = new D() as dynamic; // dynamicType as dynamic dynamic s = ""asd""; string s2 = s as dynamic; // default(dynamic) dynamic d = default(dynamic); // dynamicType as valueType : generate error int k = i2 as int; // dynamicType as refType C c4 = c3 as C; return 0; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,19): warning CS1981: Using 'is' to test compatibility with 'dynamic' // is essentially identical to testing compatibility with 'Object' and will // succeed for all non-null values Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, "123 is dynamic").WithArguments("is", "dynamic", "Object"), // (7,19): warning CS0183: The given expression is always of the provided ('dynamic') type Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "123 is dynamic").WithArguments("dynamic"), // (27,17): error CS0077: The as operator must be used with a reference type // or nullable type ('int' is a non-nullable value type) Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "i2 as int").WithArguments("int"), // (26,17): warning CS0219: The variable 'd' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName() { var text = @" class C<T> { void M(System.Type t) { M(typeof(C<C<>>)); //unbound inside bound M(typeof(C<>[])); //array of unbound M(typeof(C<>.D<int>)); //unbound containing bound M(typeof(C<int>.D<>)); //bound containing unbound M(typeof(D<,>[])); //multiple type parameters } class D<U> { } } class D<T, U> {}"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (7,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (8,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (9,25): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<>"), // (10,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<,>")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName_Nested() { var text = @" class Outer<T> { public static void Print() { System.Console.WriteLine(typeof(Inner<>)); System.Console.WriteLine(typeof(Inner<T>)); System.Console.WriteLine(typeof(Inner<int>)); System.Console.WriteLine(typeof(Outer<>.Inner<>)); System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003 System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<T>)); System.Console.WriteLine(typeof(Outer<T>.Inner<int>)); System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<int>.Inner<T>)); System.Console.WriteLine(typeof(Outer<int>.Inner<int>)); } class Inner<U> { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (11,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (12,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (14,50): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (18,52): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>")); } [Fact(), WorkItem(529583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529583")] public void CS7003ERR_UnexpectedUnboundGenericName_Attributes() { var text = @" using System; class Outer<T> { public class Inner<U> { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr : Attribute { public Attr(Type t) { } } [Attr(typeof(Outer<>.Inner<>))] [Attr(typeof(Outer<int>.Inner<>))] [Attr(typeof(Outer<>.Inner<int>))] [Attr(typeof(Outer<int>.Inner<int>))] public class Test { public static void Main() { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (21,25): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<int>.Inner<>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (22,14): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<>.Inner<int>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>")); } [Fact] public void CS7013WRN_MetadataNameTooLong() { var text = @" namespace Namespace1.Namespace2 { public interface I<T> { void Goo(); } public class OuterGenericClass<T, S> { public class NestedClass : OuterGenericClass<NestedClass, NestedClass> { } public class C : I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> { void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo() { } } } } "; // This error will necessarily have a very long error string. CreateCompilation(text).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Goo").WithArguments("Namespace1.Namespace2.I<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo")); } #endregion #region shotgun tests [Fact] public void DelegateCreationBad() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Error cases d1 = new D1(2 + 2); d1 = new D1(d3); d1 = new D1(2, 3); d1 = new D1(x: 3); d1 = new D1(M2); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (28,25): error CS0149: Method name expected // d1 = new D1(2 + 2); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2 + 2").WithLocation(28, 25), // (29,18): error CS0123: No overload for 'Program.D3.Invoke(int)' matches delegate 'Program.D1' // d1 = new D1(d3); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(d3)").WithArguments("CSSample.Program.D3.Invoke(int)", "CSSample.Program.D1").WithLocation(29, 18), // (30,25): error CS0149: Method name expected // d1 = new D1(2, 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2, 3").WithLocation(30, 25), // (31,28): error CS0149: Method name expected // d1 = new D1(x: 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "3").WithLocation(31, 28), // (32,18): error CS0123: No overload for 'M2' matches delegate 'Program.D1' // d1 = new D1(M2); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(M2)").WithArguments("M2", "CSSample.Program.D1").WithLocation(32, 18), // (16,19): warning CS0169: The field 'Program.d2' is never used // static D2 d2; Diagnostic(ErrorCode.WRN_UnreferencedField, "d2").WithArguments("CSSample.Program.d2").WithLocation(16, 19), // (17,19): warning CS0649: Field 'Program.d3' is never assigned to, and will always have its default value null // static D3 d3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "d3").WithArguments("CSSample.Program.d3", "null").WithLocation(17, 19)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut() { var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static Func<string, string> BarP => Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref Bar); // compat var z2 = new Func<string, string>(ref Baz); // compat var z3 = new Func<string, string>(ref k); // compat var z4 = new Func<string, string>(ref x => x); var z5 = new Func<string, string>(ref Goo<string>(x => x)); var z6 = new Func<string, string>(ref BarP); var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); var z8 = new Func<string, string>(ref Program.BarP); var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); var z10 = new Func<string, string>(ref Id); // compat var z11 = new Func<string, string>(ref new(x => x)); } }"; CreateCompilation(source).VerifyDiagnostics( // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(18, 43), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref Program.BarP").WithArguments("Program.BarP").WithLocation(20, 43), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,47): error CS0149: Method name expected // var z1 = new Func<string, string>(ref Bar); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 47), // (14,47): error CS0149: Method name expected // var z2 = new Func<string, string>(ref Baz); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 47), // (15,47): error CS0149: Method name expected // var z3 = new Func<string, string>(ref k); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 47), // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "BarP").WithArguments("Program.BarP").WithLocation(18, 47), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "Program.BarP").WithArguments("Program.BarP").WithLocation(20, 47), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (22,48): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref Id); // compat Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(22, 48), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_Parens() { // these are allowed in compat mode without the parenthesis // with parenthesis, it behaves like strict mode var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref (Bar)); var z2 = new Func<string, string>(ref (Baz)); var z3 = new Func<string, string>(ref (k)); var z10 = new Func<string, string>(ref (Id)); // these all are still valid for compat mode, no errors should be reported for compat mode var z4 = new Func<string, string>(ref Bar); var z5 = new Func<string, string>(ref Baz); var z6 = new Func<string, string>(ref k); var z7 = new Func<string, string>(ref Id); } }"; CreateCompilation(source).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49)); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49), // (18,47): error CS0149: Method name expected // var z4 = new Func<string, string>(ref Bar); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(18, 47), // (19,47): error CS0149: Method name expected // var z5 = new Func<string, string>(ref Baz); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(19, 47), // (20,47): error CS0149: Method name expected // var z6 = new Func<string, string>(ref k); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(20, 47), // (21,47): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z7 = new Func<string, string>(ref Id); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(21, 47)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_MultipleArgs() { var source = @" using System; public class Program { static Func<string, string> BarP => null; static void Test(Func<string, string> Baz) { var a = new Func<string, string>(ref Baz, Baz.Invoke); var b = new Func<string, string>(Baz, ref Baz.Invoke); var c = new Func<string, string>(ref Baz, ref Baz.Invoke); var d = new Func<string, string>(ref BarP, BarP.Invoke); var e = new Func<string, string>(BarP, ref BarP.Invoke); var f = new Func<string, string>(ref BarP, ref BarP.Invoke); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,46): error CS0149: Method name expected // var a = new Func<string, string>(ref Baz, Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, Baz.Invoke").WithLocation(8, 46), // (9,42): error CS0149: Method name expected // var b = new Func<string, string>(Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(9, 42), // (10,46): error CS0149: Method name expected // var c = new Func<string, string>(ref Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(10, 46), // (11,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(11, 42), // (11,46): error CS0149: Method name expected // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, BarP.Invoke").WithLocation(11, 46), // (12,42): error CS0149: Method name expected // var e = new Func<string, string>(BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(12, 42), // (13,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(13, 42), // (13,46): error CS0149: Method name expected // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(13, 46) ); } [WorkItem(538430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538430")] [Fact] public void NestedGenericAccessibility() { var text = @" public class C<T> { } public class E { class D : C<D> { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { }); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets() { var text = @" class Program { int f; int P { get; set; } int M() { return 0; } interface I { } class C { } struct S { } delegate void D(); void Test(object p) { int l = 0; Test(l<>); Test(p<>); Test(f<>); Test(P<>); Test(M<>()); Test(this.f<>); Test(this.P<>); Test(this.M<>()); System.Func<int> m; m = M<>; m = this.M<>; I<> i1 = null; C<> c1 = new C(); C c2 = new C<>(); S<> s1 = new S(); S s2 = new S<>(); D<> d1 = null; Program.I<> i2 = null; Program.C<> c3 = new Program.C(); Program.C c4 = new Program.C<>(); Program.S<> s3 = new Program.S(); Program.S s4 = new Program.S<>(); Program.D<> d2 = null; Test(default(I<>)); Test(default(C<>)); Test(default(S<>)); Test(default(Program.I<>)); Test(default(Program.C<>)); Test(default(Program.S<>)); string s; s = typeof(I<>).Name; s = typeof(C<>).Name; s = typeof(S<>).Name; s = typeof(Program.I<>).Name; s = typeof(Program.C<>).Name; s = typeof(Program.S<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0307: The variable 'l' cannot be used with type arguments // Test(l<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "l<>").WithArguments("l", "variable").WithLocation(16, 14), // (17,14): error CS0307: The variable 'object' cannot be used with type arguments // Test(p<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "p<>").WithArguments("object", "variable").WithLocation(17, 14), // (19,14): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(19, 14), // (20,14): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(20, 14), // (21,14): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(21, 14), // (23,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.f<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.f<>").WithLocation(23, 14), // (23,19): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(this.f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(23, 19), // (24,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.P<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.P<>").WithLocation(24, 14), // (24,19): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(this.P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(24, 19), // (25,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.M<>()); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(25, 14), // (25,19): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(this.M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(25, 19), // (29,13): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(29, 13), // (30,13): error CS8389: Omitting the type argument is not allowed in the current context // m = this.M<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(30, 13), // (30,18): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = this.M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(30, 18), // (32,9): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // I<> i1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(32, 9), // (33,9): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C<> c1 = new C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(33, 9), // (34,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C c2 = new C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(34, 20), // (35,9): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S<> s1 = new S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(35, 9), // (36,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S s2 = new S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(36, 20), // (37,9): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // D<> d1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(37, 9), // (39,17): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Program.I<> i2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(39, 17), // (40,17): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C<> c3 = new Program.C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(40, 17), // (41,36): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C c4 = new Program.C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(41, 36), // (42,17): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S<> s3 = new Program.S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(42, 17), // (43,36): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S s4 = new Program.S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(43, 36), // (44,17): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // Program.D<> d2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(44, 17), // (46,22): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(46, 22), // (47,22): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(47, 22), // (48,22): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(48, 22), // (50,30): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(Program.I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(50, 30), // (51,30): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(Program.C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(51, 30), // (52,30): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(Program.S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(52, 30), // (56,20): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(56, 20), // (57,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(57, 20), // (58,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(58, 20), // (60,28): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(Program.I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(60, 28), // (61,28): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(Program.C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(61, 28), // (62,28): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(Program.S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(62, 28), // (4,9): warning CS0649: Field 'Program.f' is never assigned to, and will always have its default value 0 // int f; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f").WithArguments("Program.f", "0").WithLocation(4, 9) ); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets_Events() { var text = @" class Program { event System.Action E; event System.Action F { add { } remove { } } void Test<T>(T p) { Test(E<>); Test(this.E<>); E<> += null; //parse error F<> += null; //parse error this.E<> += null; //parse error this.F<> += null; //parse error } } "; CreateCompilation(text).VerifyDiagnostics( // Parser // (12,11): error CS1525: Invalid expression term '>' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(12, 11), // (12,13): error CS1525: Invalid expression term '+=' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(12, 13), // (13,11): error CS1525: Invalid expression term '>' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(13, 11), // (13,13): error CS1525: Invalid expression term '+=' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(13, 13), // (15,16): error CS1525: Invalid expression term '>' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(15, 16), // (15,18): error CS1525: Invalid expression term '+=' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(15, 18), // (16,16): error CS1525: Invalid expression term '>' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(16, 16), // (16,18): error CS1525: Invalid expression term '+=' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(16, 18), // Binder // (9,14): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(9, 14), // (10,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.E<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.E<>").WithLocation(10, 14), // (10,19): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(this.E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(10, 19), // (13,9): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(13, 9), // (16,14): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(16, 14)); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [WorkItem(542679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542679")] [Fact] public void EmptyAngleBrackets_TypeParameters() { var text = @" class Program { void Test<T>(T p) { Test(default(T<>)); string s = typeof(T<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (6, 24): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter"), // (7,27): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_TypeWithCorrectArity() { var text = @" class C<T> { static void M() { C<>.M(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic type 'C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_MethodWithCorrectArity() { var text = @" class C { static void M<T>() { M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M<>").WithArguments("M", "method group", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedTypeWithCorrectArity() { var text = @" class A { class C<T> { static void M() { A.C<>.M(); } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,15): error CS0305: Using the generic type 'A.C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("A.C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedMethodWithCorrectArity() { var text = @" class C { static void M<T>() { C.M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C.M<>").WithArguments("M", "method group", "1")); } [Fact] public void NamesTooLong() { var longE = new String('e', 1024); var builder = new System.Text.StringBuilder(); builder.Append(@" class C { "); builder.AppendFormat("int {0}1;\n", longE); builder.AppendFormat("event System.Action {0}2;\n", longE); builder.AppendFormat("public void {0}3() {{ }}\n", longE); builder.AppendFormat("public void goo(int {0}4) {{ }}\n", longE); builder.AppendFormat("public string {0}5 {{ get; set; }}\n", longE); builder.AppendLine(@" } "); CreateCompilation(builder.ToString(), null, TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //event Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //backing field Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("add_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("remove_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 3).WithArguments(longE + 3), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 4).WithArguments(longE + 4), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments("<" + longE + 5 + ">k__BackingField"), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 1).WithArguments(longE + 1) ); } #endregion #region regression tests [WorkItem(541605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541605")] [Fact] public void CS0019ERR_ImplicitlyTypedVariableAssignedNullCoalesceExpr() { CreateCompilation(@" class Test { public static void Main() { var p = null ?? null; //CS0019 } } ").VerifyDiagnostics( // error CS0019: Operator '??' cannot be applied to operands of type '<null>' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>")); } [WorkItem(528577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528577")] [Fact(Skip = "528577")] public void CS0122ERR_InaccessibleGenericType() { CreateCompilation(@" public class Top<T> { class Outer<U> { } } public class MyClass { public static void Main() { var test = new Top<int>.Outer<string>(); } } ").VerifyDiagnostics( // (13,33): error CS0122: 'Top<int>.Outer<string>' is inaccessible due to its protection level // var test = new Top<int>.Outer<string>(); Diagnostic(ErrorCode.ERR_BadAccess, "new Top<int>.Outer<string>()").WithArguments("Top<int>.Outer<string>")); } [WorkItem(528591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528591")] [Fact] public void CS0121ERR_IncorrectErrorSpan1() { CreateCompilation(@" class Test { public static void Method1(int a, long b) { } public static void Method1(long a, int b) { } public static void Main() { Method1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Method1(int, long)' and 'Test.Method1(long, int)' // Method1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Method1").WithArguments("Test.Method1(int, long)", "Test.Method1(long, int)")); } [WorkItem(528592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528592")] [Fact] public void CS0121ERR_IncorrectErrorSpan2() { CreateCompilation(@" public class Class1 { public Class1(int a, long b) { } public Class1(long a, int b) { } } class Test { public static void Main() { var i1 = new Class1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (17,18): error CS0121: The call is ambiguous between the following methods or properties: 'Class1.Class1(int, long)' and 'Class1.Class1(long, int)' // new Class1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Class1").WithArguments("Class1.Class1(int, long)", "Class1.Class1(long, int)")); } [WorkItem(542468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542468")] [Fact] public void CS1513ERR_RbraceExpected_DevDiv9741() { var text = @" class Program { private delegate string D(); static void Main(string[] args) { D d = delegate { .ToString(); }; } } "; // Used to assert. CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 10), // (9,14): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // .ToString(); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()").WithLocation(9, 14), // (7,15): error CS1643: Not all code paths return a value in anonymous method of type 'Program.D' // D d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "Program.D").WithLocation(7, 15) ); } [WorkItem(543473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543473")] [Fact] public void CS0815ERR_CannotAssignLambdaExpressionToAnImplicitlyTypedLocalVariable() { var text = @"class Program { static void Main(string[] args) { var a1 = checked((a) => a); } }"; CreateCompilation(text).VerifyDiagnostics( // (5,26): error CS8917: The delegate type could not be inferred. // var a1 = checked((a) => a); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(a) => a").WithLocation(5, 26)); } [Fact, WorkItem(543665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543665")] public void CS0246ERR_SingleTypeNameNotFound_UndefinedTypeInDelegateSignature() { var text = @" using System; class Test { static void Main() { var d = (Action<List<int>>)delegate(List<int> t) {}; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,41): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 41), // (7,21): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 21) ); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_StaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_NestedStaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } class Inner { static readonly Program Field3 = new Program(ref Program.Field2); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,58): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor) // static readonly Program Field3 = new Program(ref Program.Field2); Diagnostic(ErrorCode.ERR_RefReadonlyStatic, "Program.Field2").WithLocation(11, 58) ); } [Fact] public void BadYield_MultipleReasons() { var source = @" using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { try { yield return 11; // CS1626 } catch { yield return 12; // CS1626 } finally { yield return 13; // CS1625 } } catch { try { yield return 21; // CS1626 } catch { yield return 22; // CS1631 } finally { yield return 23; // CS1625 } } finally { try { yield return 31; // CS1625 } catch { yield return 32; // CS1625 } finally { yield return 33; // CS1625 } } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 11; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (16,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 12; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (20,17): error CS1625: Cannot yield in the body of a finally clause // yield return 13; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (27,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 21; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (31,17): error CS1631: Cannot yield a value in the body of a catch clause // yield return 22; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (35,17): error CS1625: Cannot yield in the body of a finally clause // yield return 23; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (42,17): error CS1625: Cannot yield in the body of a finally clause // yield return 31; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (46,17): error CS1625: Cannot yield in the body of a finally clause // yield return 32; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (50,17): error CS1625: Cannot yield in the body of a finally clause // yield return 33; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield")); } [Fact] public void BadYield_Lambda() { var source = @" using System; using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { } finally { Action a = () => { yield break; }; Action b = () => { try { } finally { yield break; } }; } yield break; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,32): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // Action a = () => { yield break; }; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // CONSIDER: ERR_BadYieldInFinally is redundant, but matches dev11. // (22,21): error CS1625: Cannot yield in the body of a finally clause // yield break; Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (22,21): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield break; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield")); } #endregion [Fact] public void Bug528147() { var text = @" using System; interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void Main() { D d = M; d(null); } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0122: 'Program.M<A.B>(I<A.B>)' is inaccessible due to its protection level // D d = M; Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("Program.M<A.B>(I<A.B>)") ); } [WorkItem(630799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630799")] [Fact] public void Bug630799() { var text = @" using System; class Program { static void Goo<T,S>() where T : S where S : Exception { try { } catch(S e) { } catch(T e) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('S') // catch(T e) Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("S").WithLocation(14, 15), // (11,17): warning CS0168: The variable 'e' is declared but never used // catch(S e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(11, 17), // (14,17): warning CS0168: The variable 'e' is declared but never used // catch(T e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(14, 17) ); } [Fact] public void ConditionalMemberAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { } static void Main(string[] args) { var x = 123 ?.ToString(); var p = new Program(); var x1 = p.P1 ?.ToString(); var x2 = p.V() ?.ToString(); var x3 = p.V ?.ToString(); var x4 = ()=> { return 1; } ?.ToString(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (13,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(13, 21), // (16,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?.ToString(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(16, 18), // (17,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(17, 24), // (18,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(18, 20), // (19,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = ()=> { return 1; } ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "()=> { return 1; } ?.ToString()").WithArguments("?", "lambda expression").WithLocation(19, 18) ); } [Fact] public void ConditionalMemberAccess002_notIn5() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (14,18): error CS8026: Feature 'null propagation operator' is not available in C# 5. Please use language version 6 or greater. // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "p.P1 ?.ToString").WithArguments("null propagating operator", "6").WithLocation(14, 18), // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] public void ConditionalMemberAccess002() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23009, "https://github.com/dotnet/roslyn/issues/23009")] public void ConditionalElementAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { var x6 = base?.ToString(); } static void Main(string[] args) { var x = 123 ?[1,2]; var p = new Program(); var x1 = p.P1 ?[1,2]; var x2 = p.V() ?[1,2]; var x3 = p.V ?[1,2]; var x4 = ()=> { return 1; } ?[1,2]; var x5 = null?.ToString(); } } "; var compilation = CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,18): error CS0175: Use of keyword 'base' is not valid in this context // var x6 = base?.ToString(); Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(11, 18), // (16,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(16, 21), // (19,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?[1,2]; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(19, 18), // (20,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(20, 24), // (21,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?[1,2]; Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(21, 20), // (22,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = ()=> { return 1; } ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "()=> { return 1; } ?[1,2]").WithArguments("?", "lambda expression").WithLocation(22, 18), // (24,22): error CS0023: Operator '?' cannot be applied to operand of type '<null>' // var x5 = null?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "<null>").WithLocation(24, 22) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().First(); Assert.Equal("base?.ToString()", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: ?, IsInvalid) (Syntax: 'base?.ToString()') Operation: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base') WhenNotNull: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base') Arguments(0) "); } [Fact] [WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")] public void ConditionalMemberAccessPtr() { var text = @" using System; class Program { unsafe static void Main() { IntPtr? intPtr = null; var p = intPtr?.ToPointer(); } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,23): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // var p = intPtr?.ToPointer(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(9, 23) ); } [Fact] [WorkItem(991490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991490")] public void ConditionalMemberAccessExprLambda() { var text = @" using System; using System.Linq.Expressions; class Program { static void M<T>(T x) { Expression<Func<string>> s = () => x?.ToString(); Expression<Func<char?>> c = () => x.ToString()?[0]; Expression<Func<int?>> c1 = () => x.ToString()?.Length; Expression<Func<int?>> c2 = () => x?.ToString()?.Length; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (9,44): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<string>> s = () => x?.ToString(); Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()").WithLocation(9, 44), // (10,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<char?>> c = () => x.ToString()?[0]; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?[0]").WithLocation(10, 43), // (11,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c1 = () => x.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?.Length").WithLocation(11, 43), // (13,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()?.Length").WithLocation(13, 43), // (13,45): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, ".ToString()?.Length").WithLocation(13, 45) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda() { var text = @" using System; using System.Linq.Expressions; using System.Collections.Generic; class Program { static void M<T>(T x) { Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (10,87): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, "[1]").WithLocation(10, 87) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda1() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ConsoleApplication31 { class Program { static void Main(string[] args) { var o = new Goo(); var x = o.E.Compile()().Pop(); System.Console.WriteLine(x); } } static class StackExtensions { public static void Add<T>(this Stack<T> s, T x) => s.Push(x); } class Goo { public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (25,72): error CS8075: An expression tree lambda may not contain an extension collection element initializer. // public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, "42").WithLocation(25, 72) ); } [WorkItem(310, "https://github.com/dotnet/roslyn/issues/310")] [Fact] public void ExtensionElementInitializerInExpressionLambda() { var text = @" using System; using System.Collections; using System.Linq.Expressions; class C { static void Main() { Expression<Func<C>> e = () => new C { H = { [""Key""] = ""Value"" } }; Console.WriteLine(e); var c = e.Compile().Invoke(); Console.WriteLine(c.H[""Key""]); } readonly Hashtable H = new Hashtable(); } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (9,53): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<C>> e = () => new C { H = { ["Key"] = "Value" } }; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, @"[""Key""]").WithLocation(9, 53) ); } [WorkItem(12900, "https://github.com/dotnet/roslyn/issues/12900")] [WorkItem(17138, "https://github.com/dotnet/roslyn/issues/17138")] [Fact] public void CSharp7FeaturesInExprTrees() { var source = @" using System; //using System.Collections; using System.Linq.Expressions; class C { static void Main() { // out variable declarations Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 // pattern matching object o = 3; Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 // direct tuple creation could be OK, as it is just a constructor invocation, // not for long tuples the generated code is more complex, and we would // prefer custom expression trees to express the semantics. Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal // tuple conversions (byte, byte) t1 = (1, 2); Expression<Func<(byte a, byte b)>> e5 = () => t1; // OK, identity conversion Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method // discard Expression<Func<bool>> e8 = () => TryGetThree(out int _); Expression<Func<bool>> e9 = () => TryGetThree(out var _); Expression<Func<bool>> e10 = () => _ = (bool)o; Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Expression<Func<bool>> e14 = () => TryGetThree(out _); } static bool TryGetThree(out int three) { three = 3; return true; } static int three = 3; static ref int GetRefThree() { return ref three; } static int TakeRef(ref int x) { Console.WriteLine(""wow""); return x; } static (object, object) GetTuple() { return (null, null); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref=""System.ValueTuple""/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )] public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (34,50): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a, _)").WithLocation(34, 50), // (35,51): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var a").WithLocation(35, 51), // (10,59): error CS8198: An expression tree may not contain an out argument variable declaration. // Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x").WithLocation(10, 59), // (14,43): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "o is int y").WithLocation(14, 43), // (19,45): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, o)").WithLocation(19, 45), // (20,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, 2)").WithLocation(20, 49), // (25,49): error CS8144: An expression tree may not contain a tuple conversion. // Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, "t1").WithLocation(25, 49), // (27,54): error CS8156: An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference // Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method Diagnostic(ErrorCode.ERR_RefReturningCallInExpressionTree, "GetRefThree()").WithLocation(27, 54), // (30,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e8 = () => TryGetThree(out int _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "int _").WithLocation(30, 59), // (31,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e9 = () => TryGetThree(out var _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "var _").WithLocation(31, 59), // (32,44): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<bool>> e10 = () => _ = (bool)o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (bool)o").WithLocation(32, 44), // (33,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (_, _) = GetTuple()").WithLocation(33, 46), // (33,50): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(_, _)").WithLocation(33, 50), // (36,60): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e14 = () => TryGetThree(out _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "_").WithLocation(36, 60) ); } [Fact] public void DictionaryInitializerInCS5() { var text = @" using System.Collections.Generic; class Program { static void Main() { var s = new Dictionary<int, int> () {[1] = 2}; } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (8,46): error CS8026: Feature 'dictionary initializer' is not available in C# 5. Please use language version 6 or greater. // var s = new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "[1] = 2").WithArguments("dictionary initializer", "6").WithLocation(8, 46) ); } [Fact] public void DictionaryInitializerDataFlow() { var text = @" using System.Collections.Generic; class Program { static void Main() { int i; var s = new Dictionary<int, int> () {[i] = 2}; i = 1; System.Console.WriteLine(i); } static void Goo() { int i; var s = new Dictionary<int, int> () {[i = 1] = 2}; System.Console.WriteLine(i); } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (9,47): error CS0165: Use of unassigned local variable 'i' // var s = new Dictionary<int, int> () {[i] = 2}; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(9, 47) ); } [Fact] public void ConditionalMemberAccessNotStatement() { var text = @" class Program { static void Main() { var x = new int[10]; x?.Length; x?[1]; x?.ToString()[1]; } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.Length; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.Length").WithLocation(8, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?[1]").WithLocation(9, 9), // (10,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.ToString()[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.ToString()[1]").WithLocation(10, 9) ); } [WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")] [Fact] public void ConditionalMemberAccessRefLike() { var text = @" class Program { static void Main(string[] args) { var o = new Program(); o?.F(); // this is ok var x = o?.F(); var y = o?.F() ?? default; var z = o?.F().field ?? default; } S2 F() => throw null; } public ref struct S1 { } public ref struct S2 { public S1 field; } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (10,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var x = o?.F(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(10, 18), // (12,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var y = o?.F() ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(12, 18), // (14,18): error CS0023: Operator '?' cannot be applied to operand of type 'S1' // var z = o?.F().field ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S1").WithLocation(14, 18) ); } [Fact] [WorkItem(1179322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179322")] public void LabelSameNameAsParameter() { var text = @" class Program { static object M(object obj, object value) { if (((string)obj).Length == 0) value: new Program(); } } "; var compilation = CreateCompilation(text); compilation.GetParseDiagnostics().Verify(); // Make sure the compiler can handle producing method body diagnostics for this pattern when // queried via an API (command line compile would exit after parse errors were reported). compilation.GetMethodBodyDiagnostics().Verify( // (6,41): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "value: new Program();").WithLocation(6, 41), // (6,41): warning CS0164: This label has not been referenced // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "value").WithLocation(6, 41), // (4,19): error CS0161: 'Program.M(object, object)': not all code paths return a value // static object M(object obj, object value) Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("Program.M(object, object)").WithLocation(4, 19)); } [Fact] public void ThrowInExpressionTree() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static bool b = true; static object o = string.Empty; static void Main(string[] args) { Expression<Func<object>> e1 = () => o ?? throw null; Expression<Func<object>> e2 = () => b ? throw null : o; Expression<Func<object>> e3 = () => b ? o : throw null; Expression<Func<object>> e4 = () => throw null; } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (13,54): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e1 = () => o ?? throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(13, 54), // (14,53): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e2 = () => b ? throw null : o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(14, 53), // (15,57): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e3 = () => b ? o : throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(15, 57), // (16,49): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e4 = () => throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(16, 49) ); } [Fact, WorkItem(17674, "https://github.com/dotnet/roslyn/issues/17674")] public void VoidDiscardAssignment() { var text = @" class Program { public static void Main(string[] args) { _ = M(); } static void M() { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9) ); } [Fact, WorkItem(22880, "https://github.com/dotnet/roslyn/issues/22880")] public void AttributeCtorInParam() { var text = @" [A(1)] class A : System.Attribute { A(in int x) { } } [B()] class B : System.Attribute { B(in int x = 1) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (2,2): error CS8358: Cannot use attribute constructor 'A.A(in int)' because it has 'in' parameters. // [A(1)] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "A(1)").WithArguments("A.A(in int)").WithLocation(2, 2), // (7,2): error CS8358: Cannot use attribute constructor 'B.B(in int)' because it has 'in' parameters. // [B()] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "B()").WithArguments("B.B(in int)").WithLocation(7, 2) ); } [Fact] public void ERR_ExpressionTreeContainsSwitchExpression() { var text = @" using System; using System.Linq.Expressions; public class C { public int Test() { Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text, parseOptions: TestOptions.RegularWithRecursivePatterns).VerifyDiagnostics( // (9,45): error CS8411: An expression tree may not contain a switch expression. // Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, "a switch { 0 => 1, _ => 2 }").WithLocation(9, 45) ); } [Fact] public void PointerGenericConstraintTypes() { var source = @" namespace A { class D {} } class B {} unsafe class C<T, U, V, X, Y, Z> where T : byte* where U : unmanaged where V : U* where X : object* where Y : B* where Z : A.D* { void M1<A>() where A : byte* {} void M2<A, B>() where A : unmanaged where B : A* {} void M3<A>() where A : object* {} void M4<A>() where A : B* {} void M5<A>() where A : T {} }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (9,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // unsafe class C<T, U, V, X, Y, Z> where T : byte* Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(9, 44), // (11,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where V : U* Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(11, 44), // (12,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where X : object* Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(12, 44), // (13,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Y : B* Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(13, 44), // (14,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Z : A.D* Diagnostic(ErrorCode.ERR_BadConstraintType, "A.D*").WithLocation(14, 44), // (16,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M1<A>() where A : byte* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(16, 28), // (18,31): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where B : A* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "A*").WithLocation(18, 31), // (19,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M3<A>() where A : object* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(19, 28), // (20,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M4<A>() where A : B* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(20, 28) ); } [Fact] public void ArrayGenericConstraintTypes() { var source = @"class A<T> where T : object[] {}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,22): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // class A<T> where T : object[] {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object[]").WithLocation(1, 22)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// this place is dedicated to binding related error tests /// </summary> public class SemanticErrorTests : CompilingTestBase { #region "Targeted Error Tests - please arrange tests in the order of error code" [Fact] public void CS0019ERR_BadBinaryOps01() { var text = @" namespace x { public class b { public static void Main() { bool q = false; if (q == 1) { } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 9, Column = 17 }); } [Fact] public void CS0019ERR_BadBinaryOps02() { var text = @"using System; enum E { A, B, C } enum F { X = (E.A + E.B) * DayOfWeek.Monday } // no error class C { static void M(object o) { M((E.A + E.B) * DayOfWeek.Monday); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadBinaryOps, Line = 8, Column = 12 }); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps03() { var text = @"delegate void MyDelegate1(ref int x, out float y); class Program { public void DelegatedMethod1(ref int x, out float y) { y = 1; } public void DelegatedMethod2(out int x, ref float y) { x = 1; } public void DelegatedMethod3(out int x, float y = 1) { x = 1; } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod1; md1 += mc.DelegatedMethod2; // Invalid md1 += mc.DelegatedMethod3; // Invalid md1 -= mc.DelegatedMethod1; md1 -= mc.DelegatedMethod2; // Invalid md1 -= mc.DelegatedMethod3; // Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (21,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (22,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 += mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1"), // (24,19): error CS0123: No overload for 'DelegatedMethod2' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod2; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod2").WithArguments("DelegatedMethod2", "MyDelegate1"), // (25,19): error CS0123: No overload for 'DelegatedMethod3' matches delegate 'MyDelegate1' // md1 -= mc.DelegatedMethod3; // Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "DelegatedMethod3").WithArguments("DelegatedMethod3", "MyDelegate1") ); } // Method List to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps04() { var text = @"using System; delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; boo goo1 = new boo(abc.far); boo[] arrfoo = { p.bar, abc.far }; goo += arrfoo; // Invalid goo -= arrfoo; // Invalid goo += new boo[] { p.bar, abc.far }; // Invalid goo -= new boo[] { p.bar, abc.far }; // Invalid goo += Delegate.Combine(arrfoo); // Invalid goo += Delegate.Combine(goo, goo1); // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (16,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (17,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= arrfoo; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "arrfoo").WithArguments("boo[]", "boo"), // (18,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo += new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (19,16): error CS0029: Cannot implicitly convert type 'boo[]' to 'boo' // goo -= new boo[] { p.bar, abc.far }; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "new boo[] { p.bar, abc.far }").WithArguments("boo[]", "boo"), // (20,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(arrfoo); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(arrfoo)").WithArguments("System.Delegate", "boo"), // (21,16): error CS0266: Cannot implicitly convert type 'System.Delegate' to 'boo'. An explicit conversion exists (are you missing a cast?) // goo += Delegate.Combine(goo, goo1); // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Delegate.Combine(goo, goo1)").WithArguments("System.Delegate", "boo") ); } [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps05() { var text = @"public delegate double MyDelegate1(ref int integerPortion, out float fraction); public delegate double MyDelegate2(ref int integerPortion, out float fraction); class C { static void Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; MyDelegate2 md2 = null; md1 += md2; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0029: Cannot implicitly convert type 'MyDelegate2' to 'MyDelegate1' // md1 += md2; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "md2").WithArguments("MyDelegate2", "MyDelegate1") ); } // Anonymous method to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps06() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (7,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert anonymous method to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate (string x) { System.Console.WriteLine(x); }").WithArguments("anonymous method", "boo"), // (8,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= delegate (string x) { System.Console.WriteLine(x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Lambda expression to removal or concatenation [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps07() { var text = @"delegate void boo(int x); class C { static void Main(string[] args) { boo goo = null; goo += (string x) => { };// Invalid goo -= (string x) => { };// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (7,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (7,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (8,16): error CS1661: Cannot convert lambda expression to delegate type 'boo' because the parameter types do not match the delegate parameter types // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(string x) => { }").WithArguments("lambda expression", "boo"), // (8,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo -= (string x) => { };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int") ); } // Successive operator for addition and subtraction assignment [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps08() { var text = @"using System; delegate void boo(int x); class C { public void bar(int x) { Console.WriteLine("""", x); } static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { C p = new C(); boo goo = null; goo += p.bar + far;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far;// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (11,16): error CS0019: Operator '+' cannot be applied to operands of type 'method group' and 'method group' // goo += p.bar + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, "p.bar + far").WithArguments("+", "method group", "method group").WithLocation(11, 16), // (12,16): error CS0019: Operator '+' cannot be applied to operands of type 'lambda expression' and 'method group' // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"(x) => { System.Console.WriteLine(""Lambda:{0}"", x); } + far").WithArguments("+", "lambda expression", "method group").WithLocation(12, 16), // (12,70): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += (x) => { System.Console.WriteLine("Lambda:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(12, 70), // (13,16): error CS0019: Operator '+' cannot be applied to operands of type 'anonymous method' and 'method group' // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.ERR_BadBinaryOps, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); } + far").WithArguments("+", "anonymous method", "method group").WithLocation(13, 16), // (13,83): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // goo += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); } + far;// Invalid Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(13, 83) ); } // Removal or concatenation for the delegate on Variance [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps09() { var text = @"using System.Collections.Generic; delegate IList<int> Delegate1(List<int> x); delegate IEnumerable<int> Delegate2(IList<int> x); delegate IEnumerable<long> Delegate3(IList<long> x); class C { public static List<int> Method1(IList<int> x) { return null; } public static IList<long> Method1(IList<long> x) { return null; } static void Main(string[] args) { Delegate1 d1 = Method1; d1 += Method1; Delegate2 d2 = Method1; d2 += Method1; Delegate3 d3 = Method1; d1 += d2; // invalid d2 += d1; // invalid d2 += d3; // invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0029: Cannot implicitly convert type 'Delegate2' to 'Delegate1' // d1 += d2; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d2").WithArguments("Delegate2", "Delegate1"), // (26,15): error CS0029: Cannot implicitly convert type 'Delegate1' to 'Delegate2' // d2 += d1; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d1").WithArguments("Delegate1", "Delegate2"), // (27,15): error CS0029: Cannot implicitly convert type 'Delegate3' to 'Delegate2' // d2 += d3; // invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "d3").WithArguments("Delegate3", "Delegate2") ); } // generic-delegate (goo<t>(...)) += non generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps10() { var text = @"delegate void boo<T>(T x); class C { public void bar(int x) { System.Console.WriteLine(""bar:{0}"", x); } public void bar1(string x) { System.Console.WriteLine(""bar1:{0}"", x); } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += p.bar;// OK goo += p.bar1;// Invalid goo += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo += (string x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid boo<string> goo1 = null; goo1 += p.bar;// Invalid goo1 += p.bar1;// OK goo1 += (x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// OK goo1 += (int x) => { System.Console.WriteLine(""Lambda:{0}"", x); };// Invalid goo1 += delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// Invalid goo1 += delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); };// OK goo += goo1;// Invalid goo1 += goo;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (12,18): error CS0123: No overload for 'bar1' matches delegate 'boo<int>' // goo += p.bar1;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar1").WithArguments("bar1", "boo<int>"), // (14,16): error CS1661: Cannot convert lambda expression to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(string x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<int>"), // (14,24): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += (string x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (16,16): error CS1661: Cannot convert anonymous method to delegate type 'boo<int>' because the parameter types do not match the delegate parameter types // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (string x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<int>"), // (16,33): error CS1678: Parameter 1 is declared as type 'string' but should be 'int' // goo += delegate (string x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "string", "", "int"), // (19,19): error CS0123: No overload for 'bar' matches delegate 'boo<string>' // goo1 += p.bar;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "bar").WithArguments("bar", "boo<string>"), // (22,17): error CS1661: Cannot convert lambda expression to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"(int x) => { System.Console.WriteLine(""Lambda:{0}"", x); }").WithArguments("lambda expression", "boo<string>"), // (22,22): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += (int x) => { System.Console.WriteLine("Lambda:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (23,17): error CS1661: Cannot convert anonymous method to delegate type 'boo<string>' because the parameter types do not match the delegate parameter types // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, @"delegate (int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }").WithArguments("anonymous method", "boo<string>"), // (23,31): error CS1678: Parameter 1 is declared as type 'int' but should be 'string' // goo1 += delegate (int x) { System.Console.WriteLine("Anonymous:{0}", x); };// Invalid Diagnostic(ErrorCode.ERR_BadParamType, "x").WithArguments("1", "", "int", "", "string"), // (25,16): error CS0029: Cannot implicitly convert type 'boo<string>' to 'boo<int>' // goo += goo1;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo1").WithArguments("boo<string>", "boo<int>"), // (26,17): error CS0029: Cannot implicitly convert type 'boo<int>' to 'boo<string>' // goo1 += goo;// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "goo").WithArguments("boo<int>", "boo<string>") ); } // generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps11() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // non generic-delegate (goo<t>(...)) += generic-methodgroup(bar<t>(...)) [WorkItem(539906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539906")] [Fact] public void CS0019ERR_BadBinaryOps12() { var text = @"delegate void boo<T>(T x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo<int> goo = null; goo += far<int>;// OK goo += far<short>;// Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'far' matches delegate 'boo<int>' // goo += far<short>;// Invalid Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<short>").WithArguments("far", "boo<int>") ); } // distinguish '|' from '||' [WorkItem(540235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540235")] [Fact] public void CS0019ERR_BadBinaryOps13() { var text = @" class C { int a = 1 | 1; int b = 1 & 1; int c = 1 || 1; int d = 1 && 1; bool e = true | true; bool f = true & true; bool g = true || true; bool h = true && true; } "; CreateCompilation(text).VerifyDiagnostics( // (6,13): error CS0019: Operator '||' cannot be applied to operands of type 'int' and 'int' // int c = 1 || 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 || 1").WithArguments("||", "int", "int"), // (7,13): error CS0019: Operator '&&' cannot be applied to operands of type 'int' and 'int' // int d = 1 && 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 && 1").WithArguments("&&", "int", "int"), // (4,9): warning CS0414: The field 'C.a' is assigned but its value is never used // int a = 1 | 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("C.a"), // (5,9): warning CS0414: The field 'C.b' is assigned but its value is never used // int b = 1 & 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "b").WithArguments("C.b"), // (9,10): warning CS0414: The field 'C.e' is assigned but its value is never used // bool e = true | true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("C.e"), // (10,10): warning CS0414: The field 'C.f' is assigned but its value is never used // bool f = true & true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f"), // (11,10): warning CS0414: The field 'C.g' is assigned but its value is never used // bool g = true || true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g"), // (12,10): warning CS0414: The field 'C.h' is assigned but its value is never used // bool h = true && true; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "h").WithArguments("C.h")); } /// <summary> /// Conversion errors for Null Coalescing operator(??) /// </summary> [Fact] public void CS0019ERR_BadBinaryOps14() { var text = @" public class D { } public class Error { public int? NonNullableValueType_a(int a) { int? b = null; int? z = a ?? b; return z; } public int? NonNullableValueType_b(char ch) { char b = ch; int? z = null ?? b; return z; } public int NonNullableValueType_const_a(char ch) { char b = ch; int z = 10 ?? b; return z; } public D NoPossibleConversionError() { D b = new D(); Error a = null; D z = a ?? b; return z; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'int?' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "int", "int?"), // (13,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? b").WithArguments("??", "<null>", "char"), // (19,17): error CS0019: Operator '??' cannot be applied to operands of type 'int' and 'char' Diagnostic(ErrorCode.ERR_BadBinaryOps, "10 ?? b").WithArguments("??", "int", "char"), // (26,15): error CS0019: Operator '??' cannot be applied to operands of type 'Error' and 'D' Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? b").WithArguments("??", "Error", "D")); } [WorkItem(542115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542115")] [Fact] public void CS0019ERR_BadBinaryOps15() { var text = @"class C { static void M<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4, int i, C c) where T2 : class where T3 : struct where T4 : T1 { bool b; b = (t1 == t1); b = (t1 == t2); b = (t1 == t3); b = (t1 == t4); b = (t1 == i); b = (t1 == c); b = (t1 == null); b = (t2 == t1); b = (t2 == t2); b = (t2 == t3); b = (t2 == t4); b = (t2 == i); b = (t2 == c); b = (t2 == null); b = (t3 == t1); b = (t3 == t2); b = (t3 == t3); b = (t3 == t4); b = (t3 == i); b = (t3 == c); b = (t3 == null); b = (t4 != t1); b = (t4 != t2); b = (t4 != t3); b = (t4 != t4); b = (t4 != i); b = (t4 != c); b = (t4 != null); b = (i != t1); b = (i != t2); b = (i != t3); b = (i != t4); b = (i != i); b = (i != c); b = (i != null); b = (c != t1); b = (c != t2); b = (c != t3); b = (c != t4); b = (c != i); b = (c != c); b = (c != null); b = (null != t1); b = (null != t2); b = (null != t3); b = (null != t4); b = (null != i); b = (null != c); b = (null != null); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T1' // b = (t1 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t1").WithArguments("==", "T1", "T1"), // (10,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T2' // b = (t1 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t2").WithArguments("==", "T1", "T2"), // (11,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T3' // b = (t1 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t3").WithArguments("==", "T1", "T3"), // (12,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'T4' // b = (t1 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == t4").WithArguments("==", "T1", "T4"), // (13,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'int' // b = (t1 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == i").WithArguments("==", "T1", "int"), // (14,14): error CS0019: Operator '==' cannot be applied to operands of type 'T1' and 'C' // b = (t1 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t1 == c").WithArguments("==", "T1", "C"), // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T1' // b = (t2 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t1").WithArguments("==", "T2", "T1"), // (18,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T3' // b = (t2 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t3").WithArguments("==", "T2", "T3"), // (19,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'T4' // b = (t2 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == t4").WithArguments("==", "T2", "T4"), // (20,14): error CS0019: Operator '==' cannot be applied to operands of type 'T2' and 'int' // b = (t2 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t2 == i").WithArguments("==", "T2", "int"), // (23,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T1' // b = (t3 == t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t1").WithArguments("==", "T3", "T1"), // (24,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T2' // b = (t3 == t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t2").WithArguments("==", "T3", "T2"), // (25,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T3' // b = (t3 == t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t3").WithArguments("==", "T3", "T3"), // (26,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'T4' // b = (t3 == t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == t4").WithArguments("==", "T3", "T4"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'int' // b = (t3 == i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == i").WithArguments("==", "T3", "int"), // (28,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and 'C' // b = (t3 == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == c").WithArguments("==", "T3", "C"), // (29,14): error CS0019: Operator '==' cannot be applied to operands of type 'T3' and '<null>' // b = (t3 == null); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t3 == null").WithArguments("==", "T3", "<null>"), // (30,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T1' // b = (t4 != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t1").WithArguments("!=", "T4", "T1"), // (31,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T2' // b = (t4 != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t2").WithArguments("!=", "T4", "T2"), // (32,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T3' // b = (t4 != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t3").WithArguments("!=", "T4", "T3"), // (33,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'T4' // b = (t4 != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != t4").WithArguments("!=", "T4", "T4"), // (34,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'int' // b = (t4 != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != i").WithArguments("!=", "T4", "int"), // (35,14): error CS0019: Operator '!=' cannot be applied to operands of type 'T4' and 'C' // b = (t4 != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t4 != c").WithArguments("!=", "T4", "C"), // (37,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T1' // b = (i != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t1").WithArguments("!=", "int", "T1"), // (38,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T2' // b = (i != t2); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t2").WithArguments("!=", "int", "T2"), // (39,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T3' // b = (i != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t3").WithArguments("!=", "int", "T3"), // (40,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'T4' // b = (i != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != t4").WithArguments("!=", "int", "T4"), // (42,14): error CS0019: Operator '!=' cannot be applied to operands of type 'int' and 'C' // b = (i != c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "i != c").WithArguments("!=", "int", "C"), // (44,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T1' // b = (c != t1); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t1").WithArguments("!=", "C", "T1"), // (46,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T3' // b = (c != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t3").WithArguments("!=", "C", "T3"), // (47,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'T4' // b = (c != t4); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != t4").WithArguments("!=", "C", "T4"), // (48,14): error CS0019: Operator '!=' cannot be applied to operands of type 'C' and 'int' // b = (c != i); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c != i").WithArguments("!=", "C", "int"), // (53,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'T3' // b = (null != t3); Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != t3").WithArguments("!=", "<null>", "T3"), // (17,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (t2 == t2); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t2 == t2"), // (41,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (i != i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i != i"), // (43,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (i != null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?"), // (49,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // b = (c != c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c != c"), // (55,14): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // b = (null != i); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?")); } [Fact] public void CS0019ERR_BadBinaryOps16() { var text = @"class A { } class B : A { } interface I { } class C { static void M<T, U>(T t, U u, A a, B b, C c, I i) where T : A where U : B { bool x; x = (t == t); x = (t == u); x = (t == a); x = (t == b); x = (t == c); x = (t == i); x = (u == t); x = (u == u); x = (u == a); x = (u == b); x = (u == c); x = (u == i); x = (a == t); x = (a == u); x = (a == a); x = (a == b); x = (a == c); x = (a == i); x = (b == t); x = (b == u); x = (b == a); x = (b == b); x = (b == c); x = (b == i); x = (c == t); x = (c == u); x = (c == a); x = (c == b); x = (c == c); x = (c == i); x = (i == t); x = (i == u); x = (i == a); x = (i == b); x = (i == c); x = (i == i); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,14): error CS0019: Operator '==' cannot be applied to operands of type 'T' and 'C' // x = (t == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "t == c").WithArguments("==", "T", "C"), // (21,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and 'C' // x = (u == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == c").WithArguments("==", "U", "C"), // (27,14): error CS0019: Operator '==' cannot be applied to operands of type 'A' and 'C' // x = (a == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "a == c").WithArguments("==", "A", "C"), // (33,14): error CS0019: Operator '==' cannot be applied to operands of type 'B' and 'C' // x = (b == c); Diagnostic(ErrorCode.ERR_BadBinaryOps, "b == c").WithArguments("==", "B", "C"), // (35,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'T' // x = (c == t); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == t").WithArguments("==", "C", "T"), // (36,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'U' // x = (c == u); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == u").WithArguments("==", "C", "U"), // (37,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'A' // x = (c == a); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == a").WithArguments("==", "C", "A"), // (38,14): error CS0019: Operator '==' cannot be applied to operands of type 'C' and 'B' // x = (c == b); Diagnostic(ErrorCode.ERR_BadBinaryOps, "c == b").WithArguments("==", "C", "B"), // (11,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (t == t); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (18,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (u == u); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "u == u"), // (25,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (a == a); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "a == a"), // (32,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (b == b); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "b == b"), // (39,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (c == c); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "c == c"), // (46,14): warning CS1718: Comparison made to same variable; did you mean to compare something else? // x = (i == i); Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i")); } [Fact] public void CS0019ERR_BadBinaryOps17() { var text = @"struct S { } abstract class A<T> { internal virtual void M<U>(U u) where U : T { bool b; b = (u == null); b = (null != u); } } class B : A<S> { internal override void M<U>(U u) { bool b; b = (u == null); b = (null != u); } }"; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0019: Operator '==' cannot be applied to operands of type 'U' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "u == null").WithArguments("==", "U", "<null>").WithLocation(16, 14), // (17,14): error CS0019: Operator '!=' cannot be applied to operands of type '<null>' and 'U' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null != u").WithArguments("!=", "<null>", "U").WithLocation(17, 14)); } [Fact] public void CS0020ERR_IntDivByZero() { var text = @" namespace x { public class b { public static int Main() { int s = 1 / 0; // CS0020 return s; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 21 } }); } [Fact] public void CS0020ERR_IntDivByZero_02() { var text = @" namespace x { public class b { public static void Main() { decimal x1 = 1.20M / 0; // CS0020 decimal x2 = 1.20M / decimal.Zero; // CS0020 decimal x3 = decimal.MaxValue / decimal.Zero; // CS0020 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 9, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntDivByZero, Line = 10, Column = 26 } }); } [Fact] public void CS0021ERR_BadIndexLHS() { var text = @"enum E { } class C { static void M<T>() { object o; o = M[0]; o = ((System.Action)null)[0]; o = ((dynamic)o)[0]; o = default(E)[0]; o = default(T)[0]; o = (new C())[0]; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,13): error CS0021: Cannot apply indexing with [] to an expression of type 'method group' Diagnostic(ErrorCode.ERR_BadIndexLHS, "M[0]").WithArguments("method group").WithLocation(7, 13), // (8,13): error CS0021: Cannot apply indexing with [] to an expression of type 'System.Action' Diagnostic(ErrorCode.ERR_BadIndexLHS, "((System.Action)null)[0]").WithArguments("System.Action").WithLocation(8, 13), // (10,13): error CS0021: Cannot apply indexing with [] to an expression of type 'E' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(E)[0]").WithArguments("E").WithLocation(10, 13), // (11,13): error CS0021: Cannot apply indexing with [] to an expression of type 'T' Diagnostic(ErrorCode.ERR_BadIndexLHS, "default(T)[0]").WithArguments("T").WithLocation(11, 13), // (12,13): error CS0021: Cannot apply indexing with [] to an expression of type 'C' Diagnostic(ErrorCode.ERR_BadIndexLHS, "(new C())[0]").WithArguments("C").WithLocation(12, 13)); } [Fact] public void CS0022ERR_BadIndexCount() { var text = @" namespace x { public class b { public static void Main() { int[,] a = new int[10,2] ; a[2] = 4; //bad index count in access } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIndexCount, Line = 9, Column = 25 } }); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount02() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount03() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1 2] { 1 }; //bad index count in size specifier - with initializer } } "; // NOTE: Dev10 just gives a parse error on '2' CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments(",", ""), // (6,35): error CS0846: A nested array initializer is expected Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "1")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount04() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,]; //bad index count in size specifier - no initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(542486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542486")] [Fact] public void CS0022ERR_BadIndexCount05() { var text = @" class Program { static void Main(string[] args) { int[,] a = new int[1,] { { 1 } }; //bad index count in size specifier - with initializer } } "; CreateCompilation(text).VerifyDiagnostics( // (6,30): error CS0443: Syntax error; value expected Diagnostic(ErrorCode.ERR_ValueExpected, "")); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp1() { var text = @" namespace X { class C { object M() { object q = new object(); if (!q) // CS0023 { } object obj = -null; // CS0023 obj = !null; // CS0023 obj = ~null; // CS0023 obj++; // CS0023 --obj; // CS0023 return +null; // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '!' cannot be applied to operand of type 'object' // if (!q) // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!q").WithArguments("!", "object").WithLocation(9, 17), // (12,26): error CS8310: Operator '-' cannot be applied to operand '<null>' // object obj = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(12, 26), // (13,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // obj = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(13, 19), // (14,19): error CS8310: Operator '~' cannot be applied to operand '<null>' // obj = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(14, 19), // (16,13): error CS0023: Operator '++' cannot be applied to operand of type 'object' // obj++; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "obj++").WithArguments("++", "object").WithLocation(16, 13), // (17,13): error CS0023: Operator '--' cannot be applied to operand of type 'object' // --obj; // CS0023 Diagnostic(ErrorCode.ERR_BadUnaryOp, "--obj").WithArguments("--", "object").WithLocation(17, 13), // (18,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // return +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(18, 20) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp_Nullable() { var text = @" public class Test { public static void Main() { bool? b = !null; // CS0023 int? n = ~null; // CS0023 float? f = +null; // CS0023 long? u = -null; // CS0023 ++n; n--; --u; u++; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS8310: Operator '!' cannot be applied to operand '<null>' // bool? b = !null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(6, 19), // (7,18): error CS8310: Operator '~' cannot be applied to operand '<null>' // int? n = ~null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "~null").WithArguments("~", "<null>").WithLocation(7, 18), // (8,20): error CS8310: Operator '+' cannot be applied to operand '<null>' // float? f = +null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "+null").WithArguments("+", "<null>").WithLocation(8, 20), // (9,19): error CS8310: Operator '-' cannot be applied to operand '<null>' // long? u = -null; // CS0023 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "-null").WithArguments("-", "<null>").WithLocation(9, 19) ); } [WorkItem(539590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539590")] [Fact] public void CS0023ERR_BadUnaryOp2() { var text = @" namespace X { class C { void M() { System.Action f = M; f = +M; // CS0023 f = +(() => { }); // CS0023 } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0023: Operator '+' cannot be applied to operand of type 'method group' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+M").WithArguments("+", "method group"), // (10,17): error CS0023: Operator '+' cannot be applied to operand of type 'lambda expression' Diagnostic(ErrorCode.ERR_BadUnaryOp, "+(() => { })").WithArguments("+", "lambda expression")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidMissingInstanceMethod() { var text = @"class C { void M() { M().Goo(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540211")] [Fact] public void CS0023ERR_BadUnaryOp_VoidToString() { var text = @"class C { void M() { M().ToString(); //plausible, but still wrong } } "; CreateCompilation(text).VerifyDiagnostics( // (5,12): error CS0023: Operator '.' cannot be applied to operand of type 'void' Diagnostic(ErrorCode.ERR_BadUnaryOp, ".").WithArguments(".", "void")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] public void CS0023ERR_BadUnaryOp_null() { var text = @" class X { static void Main() { int x = null.Length; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadUnaryOp, "null.Length").WithArguments(".", "<null>")); } [WorkItem(540329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540329")] [Fact] public void CS0023ERR_BadUnaryOp_lambdaExpression() { var text = @" class X { static void Main() { System.Func<int, int> f = arg => { arg = 2; return arg; }.ToString(); var x = delegate { }.ToString(); } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadUnaryOp, "arg => { arg = 2; return arg; }.ToString").WithArguments(".", "lambda expression"), Diagnostic(ErrorCode.ERR_BadUnaryOp, "delegate { }.ToString").WithArguments(".", "anonymous method")); } [Fact] public void CS0026ERR_ThisInStaticMeth() { var text = @" public class MyClass { public static int i = 0; public static void Main() { // CS0026 this.i = this.i + 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInStaticMeth, Line = 9, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ObjectProhibited, Line = 9, Column = 18 } }); } [Fact] public void CS0026ERR_ThisInStaticMeth_StaticConstructor() { var text = @" public class MyClass { int f; void M() { } int P { get; set; } static MyClass() { this.f = this.P; this.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (10,18): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (11,9): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")); } [Fact] public void CS0026ERR_ThisInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = this.ToString(); } static object FLD = this.ToString(); static object PROP { get { return this.ToString(); } } static object METHOD() { return this.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object FLD = this.ToString(); Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (6,28): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static CLS() { var x = this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (8,39): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object PROP { get { return this.ToString(); } } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (9,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // static object METHOD() { return this.ToString(); } Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS0027ERR_ThisInBadContext() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = this.Fun() + 1; // CS0027 public void Fun() { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 6, Column = 20 } }); } [Fact] public void CS0027ERR_ThisInBadContext_2() { var text = @" using System; [assembly: A(P = this.ToString())] class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0027: Keyword 'this' is not available in the current context // [assembly: A(P = this.ToString())] Diagnostic(ErrorCode.ERR_ThisInBadContext, "this")); } [Fact] public void CS0027ERR_ThisInBadContext_Interactive() { string text = @" int a; int b = a; int c = this.a; // 1 this.c = // 2 this.a; // 3 int prop { get { return 1; } set { this.a = 1;} } // 4 void goo() { this.goo(); // 5 this.a = // 6 this.b; // 7 object c = this; // 8 } this.prop = 1; // 9 class C { C() : base() { } void goo() { this.goo(); // OK } }"; var comp = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script) }); comp.VerifyDiagnostics( // (4,9): error CS0027: Keyword 'this' is not available in the current context // int c = this.a; // 1 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(4, 9), // (5,1): error CS0027: Keyword 'this' is not available in the current context // this.c = // 2 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(5, 1), // (6,5): error CS0027: Keyword 'this' is not available in the current context // this.a; // 3 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(6, 5), // (16,1): error CS0027: Keyword 'this' is not available in the current context // this.prop = 1; // 9 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(16, 1), // (7,36): error CS0027: Keyword 'this' is not available in the current context // int prop { get { return 1; } set { this.a = 1;} } // 4 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(7, 36), // (10,5): error CS0027: Keyword 'this' is not available in the current context // this.goo(); // 5 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(10, 5), // (11,5): error CS0027: Keyword 'this' is not available in the current context // this.a = // 6 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 5), // (12,9): error CS0027: Keyword 'this' is not available in the current context // this.b; // 7 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(12, 9), // (13,16): error CS0027: Keyword 'this' is not available in the current context // object c = this; // 8 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 16) ); } [Fact] public void CS0029ERR_NoImplicitConv01() { var text = @" namespace ConsoleApplication3 { class MyClass { int err1 = 1; public string Fun() { return err1; } public static void Main() { MyClass c = new MyClass(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConv, Line = 11, Column = 20 } }); } [Fact] public void CS0029ERR_NoImplicitConv02() { var source = "enum E { A = new[] { 1, 2, 3 } }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0029: Cannot implicitly convert type 'int[]' to 'int' // enum E { A = new[] { 1, 2, 3 } } Diagnostic(ErrorCode.ERR_NoImplicitConv, "new[] { 1, 2, 3 }").WithArguments("int[]", "int").WithLocation(1, 14)); } [Fact] public void CS0029ERR_NoImplicitConv03() { var source = @"class C { static void M() { const C d = F(); } static D F() { return null; } } class D { } "; CreateCompilation(source).VerifyDiagnostics( // (5,21): error CS0029: Cannot implicitly convert type 'D' to 'C' // const C d = F(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "F()").WithArguments("D", "C").WithLocation(5, 21)); } [WorkItem(541719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541719")] [Fact] public void CS0029ERR_NoImplicitConv04() { var text = @"class C1 { public static void Main() { bool m = true; int[] arr = new int[m]; // Invalid } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type 'bool' to 'int' // int[] arr = new int[m]; // Invalid Diagnostic(ErrorCode.ERR_NoImplicitConv, "m").WithArguments("bool", "int").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // return true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 23)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void ThrowExpression_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? throw null : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0029: Cannot implicitly convert type '<throw expression>' to 'void' // object obj = true ? throw null : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "throw null").WithArguments("<throw expression>", "void").WithLocation(6, 29)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void IntLiteral_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { var obj = true ? 0 : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,19): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'void' // var obj = true ? 0 : M2(); Diagnostic(ErrorCode.ERR_InvalidQM, "true ? 0 : M2()").WithArguments("int", "void").WithLocation(6, 19) ); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Assignment() { string text = @" class C { void M1() { object obj = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "true ? M2() : M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_DiscardAssignment() { string text = @" class C { void M1() { _ = true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = true ? M2() : M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_Assignment() { string text = @" class C { void M1() { object obj = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0029: Cannot implicitly convert type 'void' to 'object' // object obj = M2(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "M2()").WithArguments("void", "object").WithLocation(6, 22)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_DiscardAssignment() { string text = @" class C { void M1() { _ = M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M2(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9)); } [Fact, WorkItem(40405, "https://github.com/dotnet/roslyn/issues/40405")] public void VoidCall_ImplicitVoidConversion_Return() { string text = @" class C { void M1() { return true ? M2() : M2(); } void M2() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.M1()' returns void, a return keyword must not be followed by an object expression // return true ? M2() : M2(); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.M1()").WithLocation(6, 9)); } [Fact] public void CS0030ERR_NoExplicitConv() { var text = @" namespace x { public class iii { public static iii operator ++(iii aa) { return (iii)0; // CS0030 } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: Cannot convert type 'int' to 'x.iii' // return (iii)0; // CS0030 Diagnostic(ErrorCode.ERR_NoExplicitConv, "(iii)0").WithArguments("int", "x.iii")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [WorkItem(920, "http://github.com/dotnet/roslyn/issues/920")] [Fact] public void CS0030ERR_NoExplicitConv02() { const string text = @" public class C { public static void Main() { decimal x = (decimal)double.PositiveInfinity; } }"; var diagnostics = CreateCompilation(text).GetDiagnostics(); var savedCurrentCulture = Thread.CurrentThread.CurrentCulture; var savedCurrentUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; try { diagnostics.Verify( // (6,21): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // decimal x = (decimal)double.PositiveInfinity; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } finally { Thread.CurrentThread.CurrentCulture = savedCurrentCulture; Thread.CurrentThread.CurrentUICulture = savedCurrentUICulture; } } [Fact] public void CS0030ERR_NoExplicitConv_Foreach() { var text = @" public class Test { static void Main(string[] args) { int[][] arr = new int[][] { new int[] { 1, 2 }, new int[] { 4, 5, 6 } }; foreach (int outer in arr) { } // invalid } }"; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int[]", "int")); } [Fact] public void CS0031ERR_ConstOutOfRange01() { var text = @"public class a { int num = (int)2147483648M; //CS0031 } "; CreateCompilation(text).VerifyDiagnostics( // (3,15): error CS0031: Constant value '2147483648M' cannot be converted to a 'int' // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(int)2147483648M").WithArguments("2147483648M", "int"), // (3,9): warning CS0414: The field 'a.num' is assigned but its value is never used // int num = (int)2147483648M; //CS0031 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "num").WithArguments("a.num")); } [WorkItem(528539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528539")] [Fact] public void CS0031ERR_ConstOutOfRange02() { var text = @" enum E : ushort { A = 10, B = -1 // CS0031 } enum F : sbyte { A = 0x7f, B = 0xf0, // CS0031 C, D = (A + 1) - 2, E = (A + 1), // CS0031 } class A { byte bt = 256; } "; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS0031: Constant value '-1' cannot be converted to a 'ushort' // B = -1 // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "-1").WithArguments("-1", "ushort").WithLocation(5, 9), // (10,9): error CS0031: Constant value '240' cannot be converted to a 'sbyte' // B = 0xf0, // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "0xf0").WithArguments("240", "sbyte").WithLocation(10, 9), // (13,10): error CS0031: Constant value '128' cannot be converted to a 'sbyte' // E = (A + 1), // CS0031 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "A + 1").WithArguments("128", "sbyte").WithLocation(13, 10), // (17,15): error CS0031: Constant value '256' cannot be converted to a 'byte' // byte bt = 256; Diagnostic(ErrorCode.ERR_ConstOutOfRange, "256").WithArguments("256", "byte").WithLocation(17, 15), // (17,10): warning CS0414: The field 'A.bt' is assigned but its value is never used // byte bt = 256; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "bt").WithArguments("A.bt").WithLocation(17, 10)); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked04() { // Confirm that we truncate the constant value before performing the range check var template = @"public class C { void M() { System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 0.9)); System.Console.WriteLine((System.Int32)(System.Int32.MaxValue + 1.0)); //CS0221 } } "; var integralTypes = new Type[] { typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), }; foreach (Type t in integralTypes) { DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(template.Replace("System.Int32", t.ToString()), new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); } } // Note that the errors for Int64 and UInt64 are not // exactly the same as for Int32, etc. above, but the // differences match the native compiler. [WorkItem(528715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528715")] [Fact] public void CS0221ERR_ConstOutOfRangeChecked05() { // Confirm that we truncate the constant value before performing the range check var text1 = @"public class C { void M() { System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 0.9)); System.Console.WriteLine((System.Int64)(System.Int64.MinValue - 1.0)); System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.Int64)(System.Int64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text1, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text2 = @"public class C { void M() { System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 0.9)); System.Console.WriteLine((System.UInt64)(System.UInt64.MinValue - 1.0)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 0.9)); //CS0221 System.Console.WriteLine((System.UInt64)(System.UInt64.MaxValue + 1.0)); //CS0221 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text2, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 7, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstOutOfRangeChecked, Line = 8, Column = 34 }); var text3 = @"class C { static void Main() { System.Console.WriteLine(long.MinValue); System.Console.WriteLine((long)(double)long.MinValue); } }"; CreateCompilation(text3).VerifyDiagnostics(); } [Fact] public void CS0034ERR_AmbigBinaryOps() { #region "Source" var text = @" public class A { // allows for the conversion of A object to int public static implicit operator int(A s) { return 0; } public static implicit operator string(A i) { return null; } } public class B { public static implicit operator int(B s) // one way to resolve this CS0034 is to make one conversion explicit // public static explicit operator int (B s) { return 0; } public static implicit operator string(B i) { return null; } public static implicit operator B(string i) { return null; } public static implicit operator B(int i) { return null; } } public class C { public static void Main() { A a = new A(); B b = new B(); b = b + a; // CS0034 // another way to resolve this CS0034 is to make a cast // b = b + (int)a; } } "; #endregion CreateCompilation(text).VerifyDiagnostics( // (47,13): error CS0034: Operator '+' is ambiguous on operands of type 'B' and 'A' // b = b + a; // CS0034 Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "b + a").WithArguments("+", "B", "A")); } [Fact] public void CS0035ERR_AmbigUnaryOp_RoslynCS0023() { var text = @" class MyClass { private int i; public MyClass(int i) { this.i = i; } public static implicit operator double(MyClass x) { return (double)x.i; } public static implicit operator decimal(MyClass x) { return (decimal)x.i; } } class MyClass2 { static void Main() { MyClass x = new MyClass(7); object o = -x; // CS0035 } }"; CreateCompilation(text).VerifyDiagnostics( // (27,20): error CS0035: Operator '-' is ambiguous on an operand of type 'MyClass' // object o = -x; // CS0035 Diagnostic(ErrorCode.ERR_AmbigUnaryOp, "-x").WithArguments("-", "MyClass")); } [Fact] public void CS0037ERR_ValueCantBeNull01() { var source = @"enum E { } struct S { } class C { static void M() { int i; i = null; i = (int)null; E e; e = null; e = (E)null; S s; s = null; s = (S)null; X x; x = null; x = (X)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (8,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 13), // (9,13): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(int)null").WithArguments("int").WithLocation(9, 13), // (11,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("E").WithLocation(11, 13), // (12,13): error CS0037: Cannot convert null to 'E' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(E)null").WithArguments("E").WithLocation(12, 13), // (14,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("S").WithLocation(14, 13), // (15,13): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(S)null").WithArguments("S").WithLocation(15, 13), // (16,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(16, 9), // (18,14): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(18, 14)); } [Fact] public void CS0037ERR_ValueCantBeNull02() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = (T1)null; o = (T2)null; o = (T3)null; o = (T4)null; o = (T5)null; o = (T6)null; o = (T7)null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0037: Cannot convert null to 'T1' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T1)null").WithArguments("T1").WithLocation(13, 13), // (15,17): error CS0037: Cannot convert null to 'T3' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T3)null").WithArguments("T3").WithLocation(15, 13), // (16,17): error CS0037: Cannot convert null to 'T4' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T4)null").WithArguments("T4").WithLocation(16, 13), // (17,17): error CS0037: Cannot convert null to 'T5' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T5)null").WithArguments("T5").WithLocation(17, 13), // (19,17): error CS0037: Cannot convert null to 'T7' because it is a non-nullable value type Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T7)null").WithArguments("T7").WithLocation(19, 13)); } [WorkItem(539589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539589")] [Fact] public void CS0037ERR_ValueCantBeNull03() { var text = @" class Program { enum MyEnum { Zero = 0, One = 1 } static int Main() { return Goo((MyEnum)null); } static int Goo(MyEnum x) { return 1; } } "; CreateCompilation(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(MyEnum)null").WithArguments("Program.MyEnum").WithLocation(12, 20)); } [Fact(), WorkItem(528875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528875")] public void CS0038ERR_WrongNestedThis() { var text = @" class OuterClass { public int count; // try the following line instead // public static int count; class InnerClass { void func() { // or, create an instance // OuterClass class_inst = new OuterClass(); // int count2 = class_inst.count; int count2 = count; // CS0038 } } public static void Main() { } }"; // Triage decided not to implement the more specific error (WrongNestedThis) and stick with ObjectRequired. var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode(649), ReportDiagnostic.Suppress } })); comp.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ObjectRequired, "count").WithArguments("OuterClass.count")); } [Fact] public void CS0039ERR_NoExplicitBuiltinConv01() { var text = @"class A { } class B: A { } class C: A { } class M { static void Main() { A a = new C(); B b = new B(); C c; // This is valid; there is a built-in reference // conversion from A to C. c = a as C; //The following generates CS0039; there is no // built-in reference conversion from B to C. c = b as C; // CS0039 } }"; CreateCompilation(text).VerifyDiagnostics( // (24,13): error CS0039: Cannot convert type 'B' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "b as C").WithArguments("B", "C").WithLocation(24, 13)); } [Fact, WorkItem(541142, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541142")] public void CS0039ERR_NoExplicitBuiltinConv02() { var text = @"delegate void D(); class C { static void M(C c) { (F as D)(); (c.F as D)(); (G as D)(); } void F() { } static void G() { } }"; CreateCompilation(text).VerifyDiagnostics( // (6,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F as D").WithLocation(6, 10), // (7,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (c.F as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "c.F as D").WithLocation(7, 10), // (8,10): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // (G as D)(); Diagnostic(ErrorCode.ERR_LambdaInIsAs, "G as D").WithLocation(8, 10)); } [Fact, WorkItem(542047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542047")] public void CS0039ERR_ConvTypeReferenceToObject() { var text = @"using System; class C { static void Main() { TypedReference a = new TypedReference(); object obj = a as object; //CS0039 } } "; CreateCompilation(text).VerifyDiagnostics( //(7,22): error CS0039: Cannot convert type 'System.TypedReference' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "a as object").WithArguments("System.TypedReference", "object").WithLocation(7, 22)); } [Fact] public void CS0069ERR_EventPropertyInInterface() { var text = @" interface I { event System.Action E1 { add; } event System.Action E2 { remove; } event System.Action E3 { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (4,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(4, 30), // (4,33): error CS0073: An add or remove accessor must have a body // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(4, 33), // (5,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 30), // (5,36): error CS0073: An add or remove accessor must have a body // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(5, 36), // (6,30): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 30), // (6,33): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 33), // (6,35): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 35), // (6,41): error CS0073: An add or remove accessor must have a body // event System.Action E3 { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 41), // (4,25): error CS0065: 'I.E1': event property must have both add and remove accessors // event System.Action E1 { add; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("I.E1").WithLocation(4, 25), // (5,25): error CS0065: 'I.E2': event property must have both add and remove accessors // event System.Action E2 { remove; } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("I.E2").WithLocation(5, 25)); } [Fact] public void CS0070ERR_BadEventUsage() { var text = @" public delegate void EventHandler(); public class A { public event EventHandler Click; public static void OnClick() { EventHandler eh; A a = new A(); eh = a.Click; } public static void Main() { } } public class B { public int mf () { EventHandler eh = new EventHandler(A.OnClick); A a = new A(); eh = a.Click; // CS0070 // try the following line instead // a.Click += eh; return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsage, Line = 26, Column = 14 } }); } [Fact] public void CS0079ERR_BadEventUsageNoField() { var text = @" public delegate void MyEventHandler(); public class Class1 { private MyEventHandler _e; public event MyEventHandler Pow { add { _e += value; } remove { _e -= value; } } public void Handler() { } public void Fire() { if (_e != null) { Pow(); // CS0079 // try the following line instead // _e(); } } public static void Main() { Class1 p = new Class1(); p.Pow += new MyEventHandler(p.Handler); p._e(); p.Pow += new MyEventHandler(p.Handler); p._e(); p._e -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } p.Pow -= new MyEventHandler(p.Handler); if (p._e != null) { p._e(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEventUsageNoField, Line = 28, Column = 13 } }); } [WorkItem(538213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538213")] [Fact] public void CS0103ERR_NameNotInContext() { var text = @" class C { static void M() { IO.File.Exists(""test""); } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "IO").WithArguments("IO").WithLocation(6, 9)); } [WorkItem(542574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542574")] [Fact] public void CS0103ERR_NameNotInContextLambdaExtension() { var text = @"using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = sourceA.Join(sourceB, a => b, b => 5, (a, b) => a + b); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(9, 48)); } [Fact()] public void CS0103ERR_NameNotInContext_foreach() { var text = @"class C { static void Main() { foreach (var y in new[] {new {y = y }}){ } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(5, 43)); } [WorkItem(528780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528780")] [Fact] public void CS0103ERR_NameNotInContext_namedAndOptional() { var text = @"using System; class NamedExample { static void Main(string[] args) { } static int CalculateBMI(int weight, int height = weight) { return (weight * 703) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,54): error CS0103: The name 'weight' does not exist in the current context // static int CalculateBMI(int weight, int height = weight) Diagnostic(ErrorCode.ERR_NameNotInContext, "weight").WithArguments("weight").WithLocation(7, 54), // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1) ); } [Fact] public void CS0118ERR_BadSKknown() { CreateCompilation( @"public class TestType {} public class MyClass { public static int Main() { TestType myTest = new TestType(); bool b = myTest is myTest; return 1; } }", parseOptions: TestOptions.Regular6) .VerifyDiagnostics( // (7,22): error CS0118: 'myTest' is a 'variable' but is used like a 'type' Diagnostic(ErrorCode.ERR_BadSKknown, "myTest").WithArguments("myTest", "variable", "type")); } [Fact] public void CS0118ERR_BadSKknown_02() { CreateCompilation(@" using System; public class P { public static void Main(string[] args) { #pragma warning disable 219 Action<args> a = null; Action<a> b = null; } }") .VerifyDiagnostics( // (6,16): error CS0118: 'args' is a variable but is used like a type // Action<args> a = null; Diagnostic(ErrorCode.ERR_BadSKknown, "args").WithArguments("args", "variable", "type").WithLocation(6, 16), // (7,16): error CS0118: 'a' is a variable but is used like a type // Action<a> b = null; Diagnostic(ErrorCode.ERR_BadSKknown, "a").WithArguments("a", "variable", "type").WithLocation(7, 16)); } [Fact] public void CS0118ERR_BadSKknown_CheckedUnchecked() { string source = @" using System; class Program { static void Main() { var z = 1; (Console).WriteLine(); // error (System).Console.WriteLine(); // error checked(Console).WriteLine(); // error checked(System).Console.WriteLine(); // error checked(z).ToString(); // ok checked(typeof(Console)).ToString(); // ok checked(Console.WriteLine)(); // ok checked(z) = 1; // ok } } "; CreateCompilation(source).VerifyDiagnostics( // (10,4): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (11,10): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable"), // (12,17): error CS0119: 'System.Console' is a type, which is not valid in the given context Diagnostic(ErrorCode.ERR_BadSKunknown, "Console").WithArguments("System.Console", "type"), // (13,17): error CS0118: 'System' is a namespace but is used like a variable Diagnostic(ErrorCode.ERR_BadSKknown, "System").WithArguments("System", "namespace", "variable")); } [WorkItem(542773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542773")] [Fact] public void CS0119ERR_BadSKunknown01_switch() { CreateCompilation( @"class A { public static void Main() { } void goo(color color1) { switch (color) { default: break; } } } enum color { blue, green } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadSKunknown, "color").WithArguments("color", "type")); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214"), WorkItem(528703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528703")] public void CS0119ERR_BadSKunknown01() { var source = @"class Test { public static void M() { int x = 0; x = (global::System.Int32) + x; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (6,14): error CS0119: 'int' is a type, which is not valid in the given context // x = (global::System.Int32) + x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type")); } [Fact] public void CS0119ERR_BadSKunknown02() { var source = @"class A { internal static object F; internal static void M() { } } class B<T, U> where T : A { static void M(T t) { U.ReferenceEquals(T.F, null); T.M(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,27): error CS0119: 'T' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (10,9): error CS0119: 'U' is a type parameter, which is not valid in the given context // U.ReferenceEquals(T.F, null); Diagnostic(ErrorCode.ERR_BadSKunknown, "U").WithArguments("U", "type parameter"), // (11,9): error CS0119: 'T' is a type parameter, which is not valid in the given context // T.M(); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type parameter"), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(541203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541203")] [Fact] public void CS0119ERR_BadSKunknown_InThrowStmt() { CreateCompilation( @"class Test { public static void M() { throw System.Exception; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Exception").WithArguments("System.Exception", "type")); } [Fact] public void CS0110ERR_CircConstValue01() { var source = @"namespace x { public class C { const int x = 1; const int a = x + b; const int b = x + c; const int c = x + d; const int d = x + e; const int e = x + a; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,19): error CS0110: The evaluation of the constant value for 'x.C.a' involves a circular definition // const int a = x + b; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("x.C.a").WithLocation(7, 19)); } [Fact] public void CS0110ERR_CircConstValue02() { var source = @"enum E { A = B, B = A } enum F { X, Y = Y } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B = A } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10), // (2,13): error CS0110: The evaluation of the constant value for 'F.Y' involves a circular definition // enum F { X, Y = Y } Diagnostic(ErrorCode.ERR_CircConstValue, "Y").WithArguments("F.Y").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue03() { var source = @"enum E { A, B = A } // no error enum F { W, X = Z, Y, Z } "; CreateCompilation(source).VerifyDiagnostics( // (2,13): error CS0110: The evaluation of the constant value for 'F.X' involves a circular definition // enum F { W, X = Z, Y, Z } Diagnostic(ErrorCode.ERR_CircConstValue, "X").WithArguments("F.X").WithLocation(2, 13)); } [Fact] public void CS0110ERR_CircConstValue04() { var source = @"enum E { A = B, B } "; CreateCompilation(source).VerifyDiagnostics( // (1,10): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // enum E { A = B, B } Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(1, 10)); } [Fact] public void CS0110ERR_CircConstValue05() { var source = @"enum E { A = C, B = C, C } "; CreateCompilation(source).VerifyDiagnostics( // (1,17): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // enum E { A = C, B = C, C } Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(1, 17)); } [Fact] public void CS0110ERR_CircConstValue06() { var source = @"class C { private const int F = (int)E.B; enum E { A = F, B } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // private const int F = (int)E.B; Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 23)); } [Fact] public void CS0110ERR_CircConstValue07() { // Should report errors from other subexpressions // in addition to circular reference. var source = @"class C { const int F = (long)(F + F + G); } "; CreateCompilation(source).VerifyDiagnostics( // (3,34): error CS0103: The name 'G' does not exist in the current context // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_NameNotInContext, "G").WithArguments("G").WithLocation(3, 34), // (3,15): error CS0110: The evaluation of the constant value for 'C.F' involves a circular definition // const int F = (long)(F + F + G); Diagnostic(ErrorCode.ERR_CircConstValue, "F").WithArguments("C.F").WithLocation(3, 15)); } [Fact] public void CS0110ERR_CircConstValue08() { // Decimal constants are special (since they're not runtime constants). var source = @"class C { const decimal D = D; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.D' involves a circular definition // const decimal D = D; Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("C.D").WithLocation(3, 19)); } [Fact] public void CS0116ERR_NamespaceUnexpected_1() { var test = @" int x; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (2,5): warning CS0168: The variable 'x' is declared but never used // int x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(2, 5) ); } [Fact] public void CS0116ERR_NamespaceUnexpected_2() { var test = @" namespace x { using System; void Method(string str) // CS0116 { Console.WriteLine(str); } } int AIProp { get ; set ; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 10, Column = 5 }); } [Fact] public void CS0116ERR_NamespaceUnexpected_3() { var test = @" namespace ns1 { goto Labl; // Invalid const int x = 1; Lab1: const int y = 2; } "; // TODO (tomat): EOFUnexpected shouldn't be reported if we enable parsing global statements in namespaces DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, // (4,5): error CS1022: Type or namespace definition, or end-of-file expected // (4,10): error CS0116: A namespace does not directly contain members such as fields or methods // (4,14): error CS1022: Type or namespace definition, or end-of-file expected // (6,5): error CS0116: A namespace does not directly contain members such as fields or methods // (6,9): error CS1022: Type or namespace definition, or end-of-file expected // (5,15): error CS0116: A namespace does not directly contain members such as fields or methods // (7,15): error CS0116: A namespace does not directly contain members such as fields or methods new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 4, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 4, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 6, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NamespaceUnexpected, Line = 7, Column = 15 }); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_4() { var test = @" delegate int D(); D d = null; "; CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = null; Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = null;").WithLocation(3, 1), // (3,3): warning CS0219: The variable 'd' is assigned but its value is never used // D d = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d").WithLocation(3, 3) ); } [WorkItem(540091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540091")] [Fact] public void CS0116ERR_NamespaceUnexpected_5() { var test = @" delegate int D(); D d = {;} "; // In this case, CS0116 is suppressed because of the syntax errors CreateCompilation(test, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // D d = {;} Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "D d = {;").WithLocation(3, 1), // (3,8): error CS1513: } expected Diagnostic(ErrorCode.ERR_RbraceExpected, ";"), // (3,9): error CS1022: Type or namespace definition, or end-of-file expected Diagnostic(ErrorCode.ERR_EOFExpected, "}"), // (3,7): error CS0622: Can only use array initializer expressions to assign to array types. Try using a new expression instead. Diagnostic(ErrorCode.ERR_ArrayInitToNonArrayType, "{")); } [WorkItem(539129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539129")] [Fact] public void CS0117ERR_NoSuchMember() { CreateCompilation( @"enum E { } class C { static void M() { C.F(E.A); C.P = C.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMember, "F").WithArguments("C", "F"), Diagnostic(ErrorCode.ERR_NoSuchMember, "A").WithArguments("E", "A"), Diagnostic(ErrorCode.ERR_NoSuchMember, "P").WithArguments("C", "P"), Diagnostic(ErrorCode.ERR_NoSuchMember, "Q").WithArguments("C", "Q")); } [Fact] public void CS0120ERR_ObjectRequired01() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static void M() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired02() { CreateCompilation( @"using System; class Program { private readonly int v = 5; delegate int del(int i); static void Main(string[] args) { del myDelegate = (int x) => x * v; Console.Write(string.Concat(myDelegate(7), ""he"")); } }") .VerifyDiagnostics( // (9,41): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' Diagnostic(ErrorCode.ERR_ObjectRequired, "v").WithArguments("Program.v")); } [Fact] public void CS0120ERR_ObjectRequired03() { var source = @"delegate int boo(); interface I { int bar(); } public struct abc : I { public int bar() { System.Console.WriteLine(""bar""); return 0x01; } } class C { static void Main(string[] args) { abc p = new abc(); boo goo = null; goo += new boo(I.bar); goo(); } }"; CreateCompilation(source, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()"), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p") ); CreateCompilation(source, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'I.bar()' // goo += new boo(I.bar); Diagnostic(ErrorCode.ERR_ObjectRequired, "I.bar").WithArguments("I.bar()").WithLocation(16, 24), // (14,13): warning CS0219: The variable 'p' is assigned but its value is never used // abc p = new abc(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "p").WithArguments("p").WithLocation(14, 13) ); } [WorkItem(543950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543950")] [Fact] public void CS0120ERR_ObjectRequired04() { CreateCompilation( @"using System; class Program { static void Main(string[] args) { var f = new Func<string>(() => ToString()); var g = new Func<int>(() => GetHashCode()); } }") .VerifyDiagnostics( // (7,40): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // var f = new Func<string>(() => ToString()); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()"), // (8,37): error CS0120: An object reference is required for the non-static field, method, or property 'object.GetHashCode()' // var g = new Func<int>(() => GetHashCode()); Diagnostic(ErrorCode.ERR_ObjectRequired, "GetHashCode").WithArguments("object.GetHashCode()") ); } [Fact] public void CS0120ERR_ObjectRequired_ConstructorInitializer() { CreateCompilation( @"class B { public B(params int[] p) { } } class C : B { int instanceField; static int staticField; int InstanceProperty { get; set; } static int StaticProperty { get; set; } int InstanceMethod() { return 0; } static int StaticMethod() { return 0; } C(int param) : base( param, instanceField, //CS0120 staticField, InstanceProperty, //CS0120 StaticProperty, InstanceMethod(), //CS0120 StaticMethod(), this.instanceField, //CS0027 C.staticField, this.InstanceProperty, //CS0027 C.StaticProperty, this.InstanceMethod(), //CS0027 C.StaticMethod()) { } } ") .VerifyDiagnostics( // (19,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.instanceField' // instanceField, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "instanceField").WithArguments("C.instanceField").WithLocation(19, 9), // (21,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceProperty' // InstanceProperty, //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceProperty").WithArguments("C.InstanceProperty").WithLocation(21, 9), // (23,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.InstanceMethod()' // InstanceMethod(), //CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "InstanceMethod").WithArguments("C.InstanceMethod()").WithLocation(23, 9), // (25,9): error CS0027: Keyword 'this' is not available in the current context // this.instanceField, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(25, 9), // (27,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceProperty, //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 9), // (29,9): error CS0027: Keyword 'this' is not available in the current context // this.InstanceMethod(), //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(29, 9), // (8,9): warning CS0649: Field 'C.instanceField' is never assigned to, and will always have its default value 0 // int instanceField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceField").WithArguments("C.instanceField", "0").WithLocation(8, 9), // (9,16): warning CS0649: Field 'C.staticField' is never assigned to, and will always have its default value 0 // static int staticField; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticField").WithArguments("C.staticField", "0").WithLocation(9, 16)); } [Fact] public void CS0120ERR_ObjectRequired_StaticConstructor() { CreateCompilation( @"class C { object field; object Property { get; set; } void Method() { } static C() { field = Property; C.field = C.Property; Method(); C.Method(); } } ") .VerifyDiagnostics( // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field").WithLocation(8, 9), // (8,17): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // field = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property").WithLocation(8, 17), // (9,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.field").WithArguments("C.field").WithLocation(9, 9), // (9,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // C.field = C.Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Property").WithArguments("C.Property").WithLocation(9, 19), // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // C.Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "C.Method").WithArguments("C.Method()").WithLocation(11, 9)); } [Fact] public void CS0120ERR_ObjectRequired_NestedClass() { CreateCompilation( @" class C { object field; object Property { get; set; } void Method() { } class D { object field2; object Property2 { get; set; } public void Goo() { object f = field; object p = Property; Method(); } public static void Bar() { object f1 = field; object p1 = Property; Method(); object f2 = field2; object p2 = Property2; Goo(); } } class E : C { public void Goo() { object f3 = field; object p3 = Property; Method(); } } }") .VerifyDiagnostics( // (15,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (16,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (17,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (22,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.field' // object f1 = field; Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("C.field"), // (23,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.Property' // object p1 = Property; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("C.Property"), // (24,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.Method()' // Method(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("C.Method()"), // (26,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.field2' // object f2 = field2; Diagnostic(ErrorCode.ERR_ObjectRequired, "field2").WithArguments("C.D.field2"), // (27,25): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Property2' // object p2 = Property2; Diagnostic(ErrorCode.ERR_ObjectRequired, "Property2").WithArguments("C.D.Property2"), // (28,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.D.Goo()' // Goo(); Diagnostic(ErrorCode.ERR_ObjectRequired, "Goo").WithArguments("C.D.Goo()"), // (4,12): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null"), // (10,16): warning CS0649: Field 'C.D.field2' is never assigned to, and will always have its default value null // object field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field2").WithArguments("C.D.field2", "null")); } [Fact, WorkItem(541505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541505")] public void CS0120ERR_ObjectRequired_Attribute() { var text = @" using System.ComponentModel; enum ProtectionLevel { Privacy = 0 } class F { [DefaultValue(Prop.Privacy)] // CS0120 ProtectionLevel Prop { get { return 0; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0120: An object reference is required for the non-static field, method, or property 'F.Prop' // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectRequired, "Prop").WithArguments("F.Prop"), // (9,17): error CS0176: Member 'ProtectionLevel.Privacy' cannot be accessed with an instance reference; qualify it with a type name instead // [DefaultValue(Prop.Privacy)] // CS0120 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Prop.Privacy").WithArguments("ProtectionLevel.Privacy") // Extra In Roslyn ); } [Fact] public void CS0121ERR_AmbigCall() { var text = @" public class C { void f(int i, double d) { } void f(double d, int i) { } public static void Main() { new C().f(1, 1); // CS0121 } }"; CreateCompilation(text).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.f(int, double)' and 'C.f(double, int)' // new C().f(1, 1); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("C.f(int, double)", "C.f(double, int)") ); } [WorkItem(539817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539817")] [Fact] public void CS0122ERR_BadAccess() { var text = @" class Base { private class P { int X; } } class Test : Base { void M() { object o = (P p) => 0; int x = P.X; int y = (P)null; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,21): error CS0122: 'Base.P' is inaccessible due to its protection level // object o = (P p) => 0; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (12,17): error CS0122: 'Base.P' is inaccessible due to its protection level // int x = P.X; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (13,18): error CS0122: 'Base.P' is inaccessible due to its protection level // int y = (P)null; Diagnostic(ErrorCode.ERR_BadAccess, "P").WithArguments("Base.P"), // (4,27): warning CS0169: The field 'Base.P.X' is never used // private class P { int X; } Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("Base.P.X")); } [WorkItem(537683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537683")] [Fact] public void CS0122ERR_BadAccess02() { var text = @"public class Outer { private class base1 { } } public class MyClass : Outer.base1 { } "; var comp = CreateCompilation(text); var type1 = comp.SourceModule.GlobalNamespace.GetMembers("MyClass").Single() as NamedTypeSymbol; var b = type1.BaseType(); var errs = comp.GetDiagnostics(); Assert.Equal(1, errs.Count()); Assert.Equal(122, errs.First().Code); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess03() { var text = @" class C1 { private C1() { } } class C2 { protected C2() { } private C2(short x) {} } class C3 : C2 { C3() : base(3) {} // CS0122 } class Test { public static int Main() { C1 c1 = new C1(); // CS0122 C2 c2 = new C2(); // CS0122 return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,12): error CS0122: 'C2.C2(short)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("C2.C2(short)"), // (21,21): error CS0122: 'C1.C1()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C1").WithArguments("C1.C1()"), // (22,21): error CS0122: 'C2.C2()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "C2").WithArguments("C2.C2()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [WorkItem(540336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540336")] [Fact] public void CS0122ERR_BadAccess04() { var text = @" class A { protected class ProtectedClass { } public class B : I<ProtectedClass> { } } interface I<T> { } class Error { static void Goo<T>(I<T> i) { } static void Main() { Goo(new A.B()); } } "; var tree = Parse(text); var compilation = CreateCompilation(tree); var model = compilation.GetSemanticModel(tree); var compilationUnit = tree.GetCompilationUnitRoot(); var classError = (TypeDeclarationSyntax)compilationUnit.Members[2]; var mainMethod = (MethodDeclarationSyntax)classError.Members[1]; var callStmt = (ExpressionStatementSyntax)mainMethod.Body.Statements[0]; var callExpr = callStmt.Expression; var callPosition = callExpr.SpanStart; var boundCall = model.GetSpeculativeSymbolInfo(callPosition, callExpr, SpeculativeBindingOption.BindAsExpression); Assert.Null(boundCall.Symbol); Assert.Equal(1, boundCall.CandidateSymbols.Length); Assert.Equal(CandidateReason.OverloadResolutionFailure, boundCall.CandidateReason); var constructedMethodSymbol = (IMethodSymbol)(boundCall.CandidateSymbols[0]); Assert.Equal("void Error.Goo<A.ProtectedClass>(I<A.ProtectedClass> i)", constructedMethodSymbol.ToTestDisplayString()); var typeArgSymbol = constructedMethodSymbol.TypeArguments.Single(); Assert.Equal("A.ProtectedClass", typeArgSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Protected inner class is inaccessible"); var paramTypeSymbol = constructedMethodSymbol.Parameters.Single().Type; Assert.Equal("I<A.ProtectedClass>", paramTypeSymbol.ToTestDisplayString()); Assert.False(model.IsAccessible(callPosition, typeArgSymbol), "Type should be inaccessible since type argument is inaccessible"); // The original test attempted to verify that "Error.Goo<A.ProtectedClass>" is an // inaccessible method when inside Error.Main. The C# specification nowhere gives // a special rule for constructed generic methods; the accessibility domain of // a method depends only on its declared accessibility and the declared accessibility // of its containing type. // // We should decide whether the answer to "is this method accessible in Main?" is // yes or no, and if no, change the implementation of IsAccessible accordingly. // // Assert.False(model.IsAccessible(callPosition, constructedMethodSymbol), "Method should be inaccessible since parameter type is inaccessible"); compilation.VerifyDiagnostics( // (16,9): error CS0122: 'Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("Error.Goo<A.ProtectedClass>(I<A.ProtectedClass>)")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess05() { var text = @" class Base { private Base() { } } class Derived : Base { private Derived() : this(1) { } //fine: can see own private members private Derived(int x) : base() { } //CS0122: cannot see base private members } "; CreateCompilation(text).VerifyDiagnostics( // (10,30): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("Base.Base()")); } [WorkItem(539628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539628")] [Fact] public void CS0122ERR_BadAccess06() { var text = @" class Base { private Base() { } //private, but a match public Base(int x) { } //public, but not a match } class Derived : Base { private Derived() { } //implicit constructor initializer } "; CreateCompilation(text).VerifyDiagnostics( // (10,13): error CS0122: 'Base.Base()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Derived").WithArguments("Base.Base()")); } [Fact] public void CS0123ERR_MethDelegateMismatch() { var text = @" delegate void D(); delegate void D2(int i); public class C { public static void f(int i) { } public static void Main() { D d = new D(f); // CS0123 D2 d2 = new D2(f); // OK } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethDelegateMismatch, Line = 11, Column = 15 } }); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [Fact] public void CS0123ERR_MethDelegateMismatch_01() { var text = @" delegate void boo(short x); class C { static void far<T>(T x) { } static void Main(string[] args) { C p = new C(); boo goo = null; goo += far<int>;// Invalid goo += far<short>;// OK } }"; CreateCompilation(text).VerifyDiagnostics( // (10,16): error CS0123: No overload for 'C.far<int>(int)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "far<int>").WithArguments("C.far<int>(int)", "boo")); } [WorkItem(539909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539909")] [WorkItem(540053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540053")] [Fact] public void CS0123ERR_MethDelegateMismatch_02() { var text = @" delegate void boo(short x); class C<T> { public static void far(T x) { } public static void par<U>(U x) { System.Console.WriteLine(""par""); } public static boo goo = null; } class D { static void Main(string[] args) { C<long> p = new C<long>(); C<long>.goo += C<long>.far; C<long>.goo += C<long>.par<byte>; C<long>.goo(byte.MaxValue); C<long>.goo(long.MaxValue); C<short>.goo(long.MaxValue); } }"; CreateCompilation(text).VerifyDiagnostics( // (15,24): error CS0123: No overload for 'C<long>.far(long)' matches delegate 'boo' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "C<long>.far").WithArguments("C<long>.far(long)", "boo").WithLocation(15, 24), // (16,32): error CS0123: No overload for 'par' matches delegate 'boo' // C<long>.goo += C<long>.par<byte>; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "par<byte>").WithArguments("par", "boo").WithLocation(16, 32), // (18,21): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(18, 21), // (19,22): error CS1503: Argument 1: cannot convert from 'long' to 'short' Diagnostic(ErrorCode.ERR_BadArgType, "long.MaxValue").WithArguments("1", "long", "short").WithLocation(19, 22) ); } [Fact] public void CS0123ERR_MethDelegateMismatch_DelegateVariance() { var text = @" delegate TOut D<out TOut, in TIn>(TIn p); class A { } class B : A { } class C : B { } class Test { static void Main() { D<B, B> d; d = F1; //CS0407 d = F2; //CS0407 d = F3; //CS0123 d = F4; d = F5; d = F6; //CS0123 d = F7; d = F8; d = F9; //CS0123 } static A F1(A p) { return null; } static A F2(B p) { return null; } static A F3(C p) { return null; } static B F4(A p) { return null; } static B F5(B p) { return null; } static B F6(C p) { return null; } static C F7(A p) { return null; } static C F8(B p) { return null; } static C F9(C p) { return null; } }"; CreateCompilation(text).VerifyDiagnostics( // (13,13): error CS0407: 'A Test.F1(A)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F1").WithArguments("Test.F1(A)", "A"), // (14,13): error CS0407: 'A Test.F2(B)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "F2").WithArguments("Test.F2(B)", "A"), // (15,13): error CS0123: No overload for 'F3' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F3").WithArguments("F3", "D<B, B>"), // (18,13): error CS0123: No overload for 'F6' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F6").WithArguments("F6", "D<B, B>"), // (21,13): error CS0123: No overload for 'F9' matches delegate 'D<B, B>' Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F9").WithArguments("F9", "D<B, B>")); } [Fact] public void CS0126ERR_RetObjectRequired() { var source = @"namespace N { class C { object F() { return; } X G() { return; } C P { get { return; } } Y Q { get { return; } } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // X G() { return; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 9), // (8,9): error CS0246: The type or namespace name 'Y' could not be found (are you missing a using directive or an assembly reference?) // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Y").WithArguments("Y").WithLocation(8, 9), // (5,22): error CS0126: An object of a type convertible to 'object' is required // object F() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(5, 22), // (6,17): error CS0126: An object of a type convertible to 'X' is required // X G() { return; } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("X").WithLocation(6, 17), // (7,21): error CS0126: An object of a type convertible to 'C' is required // C P { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("N.C").WithLocation(7, 21), // (8,21): error CS0126: An object of a type convertible to 'Y' is required // Y Q { get { return; } } Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("Y").WithLocation(8, 21)); } [WorkItem(540115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540115")] [Fact] public void CS0126ERR_RetObjectRequired_02() { var source = @"namespace Test { public delegate object D(); public class TestClass { public static int Test(D src) { src(); return 0; } } public class MainClass { public static int Main() { return TestClass.Test(delegate() { return; }); // The native compiler produces two errors for this code: // // CS0126: An object of a type convertible to 'object' is required // // CS1662: Cannot convert anonymous method to delegate type // 'Test.D' because some of the return types in the block are not implicitly // convertible to the delegate return type // // This is not great; the first error is right, but does not tell us anything about // the fact that overload resolution has failed on the first argument. The second // error is actually incorrect; it is not that 'some of the return types are incorrect', // it is that some of the returns do not return anything in the first place! There's // no 'type' to get wrong. // // I would like Roslyn to give two errors: // // CS1503: Argument 1: cannot convert from 'anonymous method' to 'Test.D' // CS0126: An object of a type convertible to 'object' is required // // Neal Gafter says: I'd like one error instead of two. There is an error inside the // body of the lambda. It is enough to report that specific error. This is consistent // with our design guideline to suppress errors higher in the tree when it is caused // by an error lower in the tree. } } } "; CreateCompilation(source).VerifyDiagnostics( // (18,48): error CS0126: An object of a type convertible to 'object' is required // return TestClass.Test(delegate() { return; }); Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("object").WithLocation(18, 48)); } [Fact] public void CS0127ERR_RetNoObjectRequired() { var source = @"namespace MyNamespace { public class MyClass { public void F() { return 0; } // CS0127 public int P { get { return 0; } set { return 0; } // CS0127, set has an implicit void return type } } } "; CreateCompilation(source).VerifyDiagnostics( // (5,27): error CS0127: Since 'MyClass.F()' returns void, a return keyword must not be followed by an object expression // public void F() { return 0; } // CS0127 Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.F()").WithLocation(5, 27), // (9,19): error CS0127: Since 'MyClass.P.set' returns void, a return keyword must not be followed by an object expression // set { return 0; } // CS0127, set has an implicit void return type Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("MyNamespace.MyClass.P.set").WithLocation(9, 19)); } [Fact] public void CS0127ERR_RetNoObjectRequired_StaticConstructor() { string text = @" class C { static C() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0127: Since 'C.C()' returns void, a return keyword must not be followed by an object expression Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.C()")); } [Fact] public void CS0128ERR_LocalDuplicate() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { char i = 'a'; int i = 2; // CS0128 if (i == 2) {} } } }"; CreateCompilation(text). VerifyDiagnostics( // (9,14): error CS0128: A local variable or function named 'i' is already defined in this scope // int i = 2; // CS0128 Diagnostic(ErrorCode.ERR_LocalDuplicate, "i").WithArguments("i").WithLocation(9, 14), // (9,14): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 2; // CS0128 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(9, 14) ); } [Fact] public void CS0131ERR_AssgLvalueExpected01() { CreateCompilation( @"class C { int i = 0; int P { get; set; } int this[int x] { get { return x; } set { } } void M() { ++P = 1; // CS0131 ++i = 1; // CS0131 ++this[0] = 1; //CS0131 } } ") .VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++P"), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++i"), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "++this[0]")); } [Fact] public void CS0131ERR_AssgLvalueExpected02() { var source = @"class C { const object NoObject = null; static void M() { const int i = 0; i += 1; 3 *= 1; (i + 1) -= 1; ""string"" = null; null = new object(); NoObject = ""string""; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // i += 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i").WithLocation(7, 9), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // 3 *= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "3").WithLocation(8, 9), // (9,10): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // (i + 1) -= 1; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "i + 1").WithLocation(9, 10), // (10,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // "string" = null; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, @"""string""").WithLocation(10, 9), // (11,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // null = new object(); Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "null").WithLocation(11, 9), // (12,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // NoObject = "string"; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "NoObject").WithLocation(12, 9)); } /// <summary> /// Breaking change from Dev10. CS0131 is now reported for all value /// types, not just struct types. Specifically, CS0131 is now reported /// for type parameters constrained to "struct". (See also CS1612.) /// </summary> [WorkItem(528763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528763")] [Fact] public void CS0131ERR_AssgLvalueExpected03() { var source = @"struct S { public object P { get; set; } public object this[object index] { get { return null; } set { } } } interface I { object P { get; set; } object this[object index] { get; set; } } class C { static void M<T>() where T : struct, I { default(S).P = null; default(T).P = null; // Dev10: no error default(S)[0] = null; default(T)[0] = null; // Dev10: no error } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S).P").WithLocation(16, 9), // (16,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T).P").WithLocation(17, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(S)[0]").WithLocation(18, 9), // (18,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T)[0]").WithLocation(19, 9)); } [WorkItem(538077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538077")] [Fact] public void CS0132ERR_StaticConstParam() { var text = @" class A { static A(int z) { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Parameters = new string[] { "A.A(int)" } } }); } [Fact] public void CS0133ERR_NotConstantExpression01() { var source = @"class MyClass { public const int a = b; //no error since b is declared const public const int b = c; //CS0133, c is not constant public static int c = 1; //change static to const to correct program } "; CreateCompilation(source).VerifyDiagnostics( // (4,25): error CS0133: The expression being assigned to 'MyClass.b' must be constant // public const int b = c; //CS0133, c is not constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "c").WithArguments("MyClass.b").WithLocation(4, 25)); } [Fact] public void CS0133ERR_NotConstantExpression02() { var source = @"enum E { X, Y = C.F(), Z = C.G() + 1, } class C { public static E F() { return E.X; } public static int G() { return 0; } } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'E' to 'int'. An explicit conversion exists (are you missing a cast?) // Y = C.F(), Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "C.F()").WithArguments("E", "int").WithLocation(4, 9), // (4,9): error CS0133: The expression being assigned to 'E.Y' must be constant // Y = C.F(), Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.F()").WithArguments("E.Y").WithLocation(4, 9), // (5,9): error CS0133: The expression being assigned to 'E.Z' must be constant // Z = C.G() + 1, Diagnostic(ErrorCode.ERR_NotConstantExpression, "C.G() + 1").WithArguments("E.Z").WithLocation(5, 9)); } [Fact] public void CS0133ERR_NotConstantExpression03() { var source = @"class C { static void M() { int y = 1; const int x = 2 * y; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0133: The expression being assigned to 'x' must be constant // const int x = 2 * y; Diagnostic(ErrorCode.ERR_NotConstantExpression, "2 * y").WithArguments("x").WithLocation(6, 23)); } [Fact] public void CS0133ERR_NotConstantExpression04() { var source = @"class C { static void M() { const int x = x + x; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,27): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 27), // (5,23): error CS0110: The evaluation of the constant value for 'x' involves a circular definition // const int x = x + x; Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("x").WithLocation(5, 23)); } [Fact] public void CS0135ERR_NameIllegallyOverrides() { // See NameCollisionTests.cs for commentary on this error. var text = @" public class MyClass2 { public static int i = 0; public static void Main() { { int i = 4; // CS0135: Roslyn reports this error here i++; } i = 0; // Native compiler reports the error here } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0135ERR_NameIllegallyOverrides02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static int x; static void Main() { int z = x; var y = from x in Enumerable.Range(1, 100) // CS1931 select x; } }").VerifyDiagnostics( // (6,16): warning CS0649: Field 'Test.x' is never assigned to, and will always have its default value 0 // static int x; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Test.x", "0").WithLocation(6, 16) ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides01() { // See comments in NameCollisionTests for thoughts on this error. string text = @"class C { static void M(object x) { string x = null; // CS0136 string y = null; if (x != null) { int y = 0; // CS0136 M(y); } M(x); M(y); } object P { get { int value = 0; // no error return value; } set { int value = 0; // CS0136 M(value); } } static void N(int q) { System.Func<int, int> f = q=>q; // 0136 } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17), // (30,35): error CS0136: A local or parameter named 'q' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // System.Func<int, int> f = q=>q; // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "q").WithArguments("q").WithLocation(30, 35)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,16): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x = null; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(5, 16), // (9,17): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int y = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(9, 17), // (24,17): error CS0136: A local or parameter named 'value' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int value = 0; // CS0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value").WithLocation(24, 17)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { static void M(object o) { try { } catch (System.IO.IOException e) { M(e); } catch (System.Exception e) // Legal; the two 'e' variables are in non-overlapping declaration spaces { M(e); } try { } catch (System.Exception o) // CS0136: Illegal; the two 'o' variables are in overlapping declaration spaces. { M(o); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "o").WithArguments("o").WithLocation(19, 33)); } [Fact] public void CS0136ERR_LocalIllegallyOverrides03() { // See comments in NameCollisionTests for commentary on this error. CreateCompilation( @"class C { int field = 0; int property { get; set; } static public void Main() { int[] ints = new int[] { 1, 2, 3 }; string[] strings = new string[] { ""1"", ""2"", ""3"" }; int conflict = 1; System.Console.WriteLine(conflict); foreach (int field in ints) { } // Legal: local hides field but name is used consistently foreach (string property in strings) { } // Legal: local hides property but name is used consistently foreach (string conflict in strings) { } // 0136: local hides another local in an enclosing local declaration space. } } ") .VerifyDiagnostics( // (14,25): error CS0136: A local or parameter named 'conflict' cannot be declared in this // scope because that name is used in an enclosing local scope to define a local or parameter // foreach (string conflict in strings) { } // 0136 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "conflict").WithArguments("conflict").WithLocation(14, 25), // (3,9): warning CS0414: The field 'C.field' is assigned but its value is never used // int field = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field")); } [WorkItem(538045, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538045")] [Fact] public void CS0139ERR_NoBreakOrCont() { var text = @" namespace x { public class a { public static void Main(bool b) { if (b) continue; // CS0139 else break; // CS0139 } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 9, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoBreakOrCont, Line = 11, Column = 17 }}); } [WorkItem(542400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542400")] [Fact] public void CS0140ERR_DuplicateLabel() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { label1: int i = M(); label1: int j = M(); // CS0140, comment this line to resolve goto label1; } static int M() { return 0; } } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,10): error CS0140: The label 'label1' is a duplicate // label1: int j = M(); // CS0140, comment this line to resolve Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(9, 10) ); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_Attribute() { var text = @" using A; using B; using System; namespace A { class var { } class XAttribute : Attribute { } } namespace B { class var { } class XAttribute : Attribute { } class X : Attribute { } } class Xyzzy { [X] // 17.2 If an attribute class is found both with and without this suffix, an ambiguity is present and a compile-time error occurs. public static void Main(string[] args) { } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); } [WorkItem(542420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542420")] [Fact] public void ErrorMeansSuccess_var() { var text = @" using A; using B; namespace A { class var { } } namespace B { class var { } } class Xyzzy { public static void Main(string[] args) { var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... } static int M() { return 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (21,9): error CS0104: 'var' is an ambiguous reference between 'A.var' and 'B.var' // var x = M(); // 8.5.1 When the local-variable-type is specified as var and no type named var is in scope, ... Diagnostic(ErrorCode.ERR_AmbigContext, "var").WithArguments("var", "A.var", "B.var") ); } [Fact] public void CS0144ERR_NoNewAbstract() { var text = @" interface ii { } abstract class aa { } public class a { public static void Main() { ii xx = new ii(); // CS0144 ii yy = new ii(Error); // CS0144, CS0103 aa zz = new aa(); // CS0144 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 14, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 15, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNewAbstract, Line = 16, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 15, Column = 22 } }); } [WorkItem(539583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539583")] [Fact] public void CS0150ERR_ConstantExpected() { var test = @" class C { static void Main() { byte x = 1; int[] a1 = new int[x]; int[] a2 = new int[x] { 1 }; //CS0150 const sbyte y = 1; const short z = 2; int[] b1 = new int[y + z]; int[] b2 = new int[y + z] { 1, 2, 3 }; } } "; CreateCompilation(test).VerifyDiagnostics( // (8,28): error CS0150: A constant value is expected Diagnostic(ErrorCode.ERR_ConstantExpected, "x")); } [Fact()] public void CS0151ERR_IntegralTypeValueExpected() { var text = @" public class iii { public static implicit operator int (iii aa) { return 0; } public static implicit operator long (iii aa) { return 0; } public static void Main() { iii a = new iii(); switch (a) // CS0151, compiler cannot choose between int and long { case 1: break; } } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (18,15): error CS0151: A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier. // switch (a) // CS0151, compiler cannot choose between int and long Diagnostic(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, "a").WithLocation(18, 15), // (20,15): error CS0029: Cannot implicitly convert type 'int' to 'iii' // case 1: Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "iii").WithLocation(20, 15) ); } [Fact] public void CS0152ERR_DuplicateCaseLabel() { var text = @" namespace x { public class a { public static void Main() { int i = 0; switch (i) { case 1: i++; return; case 1: // CS0152, two case 1 statements i++; return; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (16,13): error CS0152: The switch statement contains multiple cases with the label value '1' // case 1: // CS0152, two case 1 statements Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "case 1:").WithArguments("1").WithLocation(16, 13) ); } [Fact] public void CS0153ERR_InvalidGotoCase() { var text = @" public class a { public static void Main() { goto case 5; // CS0153 } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,7): error CS0153: A goto case is only valid inside a switch statement // goto case 5; // CS0153 Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto case 5;").WithLocation(6, 7)); } [Fact] public void CS0153ERR_InvalidGotoCase_2() { var text = @" class Program { static void Main(string[] args) { string Fruit = ""Apple""; switch (Fruit) { case ""Banana"": break; default: break; } goto default; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS0153: A goto case is only valid inside a switch statement // goto default; Diagnostic(ErrorCode.ERR_InvalidGotoCase, "goto default;").WithLocation(14, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet01() { CreateCompilation( @"class C { static object P { set { } } static int Q { set { } } static void M(object o) { C.P = null; o = C.P; // CS0154 M(P); // CS0154 ++C.Q; // CS0154 } } ") .VerifyDiagnostics( // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.P").WithArguments("C.P"), // (9,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P"), // (10,11): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C.Q").WithArguments("C.Q")); } [Fact] public void CS0154ERR_PropertyLacksGet02() { var source = @"class A { public virtual A P { get; set; } public object Q { set { } } } class B : A { public override A P { set { } } void M() { M(Q); // CS0154, no get method } static void M(B b) { object o = b.P; // no error o = b.Q; // CS0154, no get method b.P.Q = null; // no error o = b.P.Q; // CS0154, no get method } static void M(object o) { } } "; CreateCompilation(source).VerifyDiagnostics( // (11,11): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // M(Q); // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("A.Q").WithLocation(11, 11), // (16,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.Q").WithArguments("A.Q").WithLocation(16, 13), // (18,13): error CS0154: The property or indexer 'A.Q' cannot be used in this context because it lacks the get accessor // o = b.P.Q; // CS0154, no get method Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P.Q").WithArguments("A.Q").WithLocation(18, 13)); } [Fact] public void CS0154ERR_PropertyLacksGet03() { var source = @"class C { int P { set { } } void M() { P += 1; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // P += 1; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(6, 9)); } [Fact] public void CS0154ERR_PropertyLacksGet04() { var source = @"class C { object p; object P { set { p = P; } } } "; CreateCompilation(source).VerifyDiagnostics( // (4,26): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // object P { set { p = P; } } Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(4, 26)); } [Fact] public void CS0154ERR_PropertyLacksGet05() { CreateCompilation( @"class C { object P { set { } } static bool Q { set { } } void M() { object o = P as string; o = P ?? Q; o = (o != null) ? P : Q; o = !Q; } }") .VerifyDiagnostics( // (7,20): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(7, 20), // (8,13): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(8, 13), // (8,18): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(8, 18), // (9,27): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "P").WithArguments("C.P").WithLocation(9, 27), // (9,31): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(9, 31), // (10,14): error CS0154: The property or indexer 'C.Q' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Q").WithArguments("C.Q").WithLocation(10, 14)); } [Fact] public void CS0154ERR_PropertyLacksGet06() { CreateCompilation( @"class C { int this[int x] { set { } } void M(int b) { b = this[0]; b = 1 + this[1]; M(this[2]); this[3]++; this[4] += 1; } }") .VerifyDiagnostics( // (6,13): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[0]").WithArguments("C.this[int]"), // (7,17): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[1]").WithArguments("C.this[int]"), // (8,11): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[2]").WithArguments("C.this[int]"), // (9,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[3]").WithArguments("C.this[int]"), // (10,9): error CS0154: The property or indexer 'C.this[int]' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "this[4]").WithArguments("C.this[int]")); } [Fact] public void CS0154ERR_PropertyLacksGet07() { var source1 = @"public class A { public virtual object P { private get { return null; } set { } } } public class B : A { public override object P { set { } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,17): error CS0154: The property or indexer 'B.P' cannot be used in this context because it lacks the get accessor Diagnostic(ErrorCode.ERR_PropertyLacksGet, "b.P").WithArguments("B.P").WithLocation(5, 17)); } [Fact] public void CS0155ERR_BadExceptionType() { var text = @"interface IA { } interface IB : IA { } struct S { } class C { static void M() { try { } catch (object) { } catch (System.Exception) { } catch (System.DateTime) { } catch (System.Int32) { } catch (IA) { } catch (IB) { } catch (S) { } catch (S) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExceptionType, "object").WithLocation(9, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.Exception").WithArguments("object").WithLocation(10, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.DateTime").WithLocation(11, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "System.Int32").WithLocation(12, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IA").WithLocation(13, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "IB").WithLocation(14, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(15, 16), Diagnostic(ErrorCode.ERR_BadExceptionType, "S").WithLocation(16, 16)); } [Fact] public void CS0155ERR_BadExceptionType_Null() { var text = @"class C { static readonly bool False = false; const string T = null; static void M(object o) { const string s = null; if (False) throw null; if (False) throw (string)null; //CS0155 if (False) throw s; //CS0155 if (False) throw T; //CS0155 } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw (string)null; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "(string)null").WithArguments("string", "System.Exception").WithLocation(10, 26), // (11,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw s; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "s").WithArguments("string", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'string' to 'System.Exception' // if (False) throw T; //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "T").WithArguments("string", "System.Exception").WithLocation(12, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_FailingAs() { var text = @" class C { static readonly bool False = false; static void M(object o) { if (False) throw new C() as D; //CS0155, though always null } } class D : C { } "; CreateCompilation(text).VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'D' to 'System.Exception' // if (False) throw new C() as D; //CS0155, though always null Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C() as D").WithArguments("D", "System.Exception").WithLocation(8, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_TypeParameters() { var text = @"using System; class C { static readonly bool False = false; static void M<T, TC, TS, TE>(object o) where TC : class where TS : struct where TE : Exception, new() { if (False) throw default(T); //CS0155 if (False) throw default(TC); //CS0155 if (False) throw default(TS); //CS0155 if (False) throw default(TE); if (False) throw new TE(); } } "; CreateCompilation(text).VerifyDiagnostics( // (11,26): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception' // if (False) throw default(T); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(T)").WithArguments("T", "System.Exception").WithLocation(11, 26), // (12,26): error CS0029: Cannot implicitly convert type 'TC' to 'System.Exception' // if (False) throw default(TC); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TC)").WithArguments("TC", "System.Exception").WithLocation(12, 26), // (13,26): error CS0029: Cannot implicitly convert type 'TS' to 'System.Exception' // if (False) throw default(TS); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConv, "default(TS)").WithArguments("TS", "System.Exception").WithLocation(13, 26) ); } [Fact()] public void CS0155ERR_BadExceptionType_UserDefinedConversions() { var text = @"using System; class C { static readonly bool False = false; static void M(object o) { if (False) throw new Implicit(); //CS0155 if (False) throw new Explicit(); //CS0155 if (False) throw (Exception)new Implicit(); if (False) throw (Exception)new Explicit(); } } class Implicit { public static implicit operator Exception(Implicit i) { return null; } } class Explicit { public static explicit operator Exception(Explicit i) { return null; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Implicit()"), // (8,20): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "new Explicit()") ); CreateCompilation(text).VerifyDiagnostics( // (9,26): error CS0266: Cannot implicitly convert type 'Explicit' to 'System.Exception'. An explicit conversion exists (are you missing a cast?) // if (False) throw new Explicit(); //CS0155 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new Explicit()").WithArguments("Explicit", "System.Exception").WithLocation(9, 26) ); } [Fact] public void CS0155ERR_BadExceptionType_Dynamic() { var text = @" class C { static readonly bool False = false; static void M(object o) { dynamic d = null; if (False) throw d; //CS0155 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (9,26): error CS0155: The type caught or thrown must be derived from System.Exception Diagnostic(ErrorCode.ERR_BadExceptionType, "d")); CreateCompilation(text).VerifyDiagnostics(); // dynamic conversion to Exception } [WorkItem(542995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542995")] [Fact] public void CS0155ERR_BadExceptionType_Struct() { var text = @" public class Test { public static void Main(string[] args) { } private void Method() { try { } catch (s1 s) { } } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (12,16): error CS0155: The type caught or thrown must be derived from System.Exception // catch (s1 s) Diagnostic(ErrorCode.ERR_BadExceptionType, "s1"), // (12,19): warning CS0168: The variable 's' is declared but never used // catch (s1 s) Diagnostic(ErrorCode.WRN_UnreferencedVar, "s").WithArguments("s") ); } [Fact] public void CS0156ERR_BadEmptyThrow() { var text = @" using System; namespace x { public class b : Exception { } public class a { public static void Main() { try { throw; // CS0156 } catch(b) { throw; // this throw is valid } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadEmptyThrow, Line = 16, Column = 13 } }); } [Fact] public void CS0156ERR_BadEmptyThrow_Nesting() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; //avoid unreachable code if (b) throw; //CS0156 try { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } catch { if (b) throw; //fine try { if (b) throw; //fine } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 try { if (b) throw; //CS0724 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0724 } } } finally { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (9,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (12,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (20,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (36,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (41,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (44,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (52,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [Fact] public void CS0156ERR_BadEmptyThrow_Lambdas() { var text = @" class C { void M() { bool b = System.DateTime.Now.Second > 1; // avoid unreachable code System.Action a; a = () => { throw; }; //CS0156 try { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } catch { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } finally { a = () => { if (b) throw; //CS0156 try { if (b) throw; //CS0156 } catch { if (b) throw; //fine } finally { if (b) throw; //CS0156 } }; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (13,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (16,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (24,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (32,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (35,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (43,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (51,24): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (54,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw"), // (62,28): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw")); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave01() { var text = @"class C { static int F; static void M() { if (F == 0) goto Before; else if (F == 1) goto After; Before: ; try { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto TryBlock; else if (F == 3) return; TryBlock: ; } catch (System.Exception) { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto CatchBlock; else if (F == 3) return; CatchBlock: ; } finally { if (F == 0) goto Before; else if (F == 1) goto After; else if (F == 2) goto FinallyBlock; else if (F == 3) return; FinallyBlock: ; } After: ; } }"; CreateCompilation(text).VerifyDiagnostics( // (41,17): error CS0157: Control cannot leave the body of a finally clause // goto Before; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (43,17): error CS0157: Control cannot leave the body of a finally clause // goto After; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (47,17): error CS0157: Control cannot leave the body of a finally clause // return; Diagnostic(ErrorCode.ERR_BadFinallyLeave, "return"), // (3,16): warning CS0649: Field 'C.F' is never assigned to, and will always have its default value 0 // static int F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "0") ); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave02() { var text = @"using System; class C { static void F(int i) { } static void M() { for (int i = 0; i < 10;) { if (i < 5) { try { F(i); } catch (Exception) { continue; } finally { break; } } else { try { F(i); } catch (Exception) { break; } finally { continue; } } } } }"; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadFinallyLeave, "break").WithLocation(15, 27), Diagnostic(ErrorCode.ERR_BadFinallyLeave, "continue").WithLocation(21, 27)); } [WorkItem(540817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540817")] [Fact] public void CS0157ERR_BadFinallyLeave03() { var text = @" class C { static void Main(string[] args) { int i = 0; try { i = 1; } catch { i = 2; } finally { i = 3; goto lab1; }// invalid lab1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (9,26): error CS0157: Control cannot leave the body of a finally clause // finally { i = 3; goto lab1; }// invalid Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto"), // (6,13): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i") ); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow() { var text = @" namespace MyNamespace { public class MyClass { public static void Main() { goto lab1; lab1: { lab1: goto lab1; // CS0158 } } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelShadow, Line = 11, Column = 13 } }); } [WorkItem(539890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539890")] [Fact] public void CS0158ERR_LabelShadow_02() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del p = x => { goto label1; label1: // invalid return x * x; }; label1: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,9): error CS0158: The label 'label1' shadows another label by the same name in a contained scope // label1: // invalid Diagnostic(ErrorCode.ERR_LabelShadow, "label1").WithArguments("label1"), // (13,5): warning CS0164: This label has not been referenced // label1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1") ); } [WorkItem(539875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539875")] [Fact] public void CS0159ERR_LabelNotFound() { var text = @" public class Cls { public static void Main() { goto Label2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LabelNotFound, Line = 6, Column = 14 } }); } [WorkItem(528799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528799")] [Fact()] public void CS0159ERR_LabelNotFound_2() { var text = @" class Program { static void Main(string[] args) { int s = 23; switch (s) { case 21: break; case 23: goto default; } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,17): error CS0159: No such label 'default:' within the scope of the goto statement // goto default; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto default;").WithArguments("default:"), // (11,13): error CS8070: Control cannot fall out of switch from final case label ('case 23:') // case 23: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 23:").WithArguments("case 23:")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_3() { var text = @" class Program { static void Main(string[] args) { goto Label; } public static void Goo() { Label: ; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_4() { var text = @" class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Label: i++; } goto Label; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label").WithArguments("Label"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_5() { var text = @" class Program { static void Main(string[] args) { if (true) { Label1: goto Label2; } else { Label2: goto Label1; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "Label2").WithArguments("Label2"), Diagnostic(ErrorCode.ERR_LabelNotFound, "Label1").WithArguments("Label1"), Diagnostic(ErrorCode.WRN_UnreachableCode, "Label2"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "Label2")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_6() { var text = @" class Program { static void Main(string[] args) { { goto L; } { L: return; } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "L").WithArguments("L"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "L")); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_7() { var text = @" class Program { static void Main(string[] args) { int i = 3; if (true) { label1: goto label3; if (!false) { label2: goto label5; if (i > 2) { label3: goto label2; if (i == 3) { label4: if (i < 5) { label5: if (i == 4) { } else { System.Console.WriteLine(""a""); } } } } } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "label3").WithArguments("label3"), Diagnostic(ErrorCode.ERR_LabelNotFound, "label5").WithArguments("label5"), Diagnostic(ErrorCode.WRN_UnreachableCode, "if"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label4"), Diagnostic(ErrorCode.WRN_UnreachableCode, "label5"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label3"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label4"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label5")); } [WorkItem(540818, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540818")] [Fact] public void CS0159ERR_LabelNotFound_8() { var text = @" delegate int del(int i); class C { static void Main(string[] args) { del q = x => { goto label2; // invalid return x * x; }; label2: return; } } "; CreateCompilation(text). VerifyDiagnostics( // (10,17): warning CS0162: Unreachable code detected // return x * x; Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), // (9,17): error CS0159: No such label 'label2' within the scope of the goto statement // goto label2; // invalid Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label2"), // (12,5): warning CS0164: This label has not been referenced // label2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2") ); } [WorkItem(539876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539876")] [Fact] public void CS0159ERR_LabelNotFound_9() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { goto innerLoop; foreach (char y in x) { innerLoop: return; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LabelNotFound, "innerLoop").WithArguments("innerLoop"), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "innerLoop")); } [Fact] public void CS0160ERR_UnreachableCatch() { var text = @"using System; using System.IO; class A : Exception { } class B : A { } class C : IOException { } interface I { } class D : Exception, I { } class E : IOException, I { } class F<T> : Exception { } class Program { static void M() { try { } catch (A) { } catch (D) { } catch (E) { } catch (IOException) { } catch (C) { } catch (F<bool>) { } catch (F<int>) { } catch (Exception) { } catch (B) { } catch (StackOverflowException) { } catch (F<int>) { } catch (F<float>) { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "C").WithArguments("System.IO.IOException").WithLocation(19, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(23, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "StackOverflowException").WithArguments("System.Exception").WithLocation(24, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<int>").WithArguments("F<int>").WithLocation(25, 16), Diagnostic(ErrorCode.ERR_UnreachableCatch, "F<float>").WithArguments("System.Exception").WithLocation(26, 16)); } [Fact] public void CS0160ERR_UnreachableCatch_Filter1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { int a = 1; try { } catch when (a == 1) { } catch (Exception e) when (e.Message == null) { } catch (A) { } catch (B e) when (e.Message == null) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('A') // catch (B e) when (e.Message == null) { } Diagnostic(ErrorCode.ERR_UnreachableCatch, "B").WithArguments("A").WithLocation(15, 16)); } [Fact] public void CS8359WRN_FilterIsConstantFalse_NonBoolean() { // Non-boolean constant filters are not considered for WRN_FilterIsConstant warnings. var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (1) { } catch (B) when (0) { } catch (B) when (""false"") { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (A) when (1) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool").WithLocation(11, 25), // (12,25): error CS0029: Cannot implicitly convert type 'int' to 'bool' // catch (B) when (0) { } Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "bool").WithLocation(12, 25), // (13,25): error CS0029: Cannot implicitly convert type 'string' to 'bool' // catch (B) when ("false") { } Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""false""").WithArguments("string", "bool").WithLocation(13, 25), // (14,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(14, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse2() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } catch (B) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "(1+1)!=2").WithLocation(11, 25), // (12,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (B) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 25)); } [Fact] public void CS8359WRN_FilterIsConstantFalse3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } finally { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch1() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 25)); } [Fact] public void CS8360WRN_FilterIsConstantRedundantTryCatch2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch (A) when ((1+1)!=2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8360: Filter expression is a constant 'false', consider removing the try-catch block // catch (A) when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "(1+1)!=2").WithLocation(10, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue1() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (true) { } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (A) when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(11, 25)); } [Fact] public void CS7095WRN_FilterIsConstantTrue2() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when (true) { } catch (A) { } catch when (false) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 21), // (12,19): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch when (false) { } Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(12, 21)); } [Fact] public void CS7095WRN_FilterIsConstantTrue3() { var text = @" using System; class A : Exception { } class Program { static void M() { try { } catch when ((1+1)==2) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,19): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch when (true) { } Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "(1+1)==2").WithLocation(10, 21)); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition() { var text = @" using System; class A : Exception { } class B : A { } class Program { static void M() { try { } catch (A) when (false) { Console.WriteLine(1); } catch (B) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,25): warning CS8359: Filter expression is a constant 'false', consider removing the catch clause // catch (A) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalse, "false").WithLocation(11, 25), // (13,13): warning CS0162: Unreachable code detected // Console.WriteLine(1); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(13, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition2() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (false) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7105: Filter expression is a constant 'false', consider removing the try-catch block // catch (Exception) when (false) Diagnostic(ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch, "false").WithLocation(10, 33), // (12,13): warning CS0162: Unreachable code detected // Console.WriteLine(x); Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(12, 13) ); } [Fact] public void CS0162WRN_UnreachableCode_Filter_ConstantCondition3() { var text = @" using System; class Program { static void M() { int x; try { } catch (Exception) when (true) { Console.WriteLine(x); } } } "; // Unlike an unreachable code in if statement block we don't allow using // a variable that's not definitely assigned. The reason why we allow it in an if statement // is to make conditional compilation easier. Such scenario doesn't apply to filters. CreateCompilation(text).VerifyDiagnostics( // (10,33): warning CS7095: Filter expression is a constant 'true', consider removing the filter // catch (Exception) when (true) Diagnostic(ErrorCode.WRN_FilterIsConstantTrue, "true").WithLocation(10, 33), // (12,31): error CS0165: Use of unassigned local variable 'x' // Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(12, 31) ); } [Fact] public void CS0160ERR_UnreachableCatch_Dynamic() { string source = @" using System; public class EG<T> : Exception { } public class A { public void M1() { try { Goo(); } catch (EG<object>) { } catch (EG<dynamic>) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (17,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "EG<dynamic>").WithArguments("EG<object>")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter() { string source = @" using System; public class EA : Exception { } public class EB : EA { } public class A<T> where T : EB { public void M1() { try { Goo(); } catch (EA) { } catch (T) { } } void Goo() { } }"; CreateCompilation(source).VerifyDiagnostics( // (18,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EA') Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("EA")); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic1() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<dynamic>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<dynamic>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<dynamic>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<dynamic>")); } [Fact] public void TypeParameter_DynamicConversions() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { V v = default(V); U u = default(U); // implicit EG<dynamic> egd = v; // implicit egd = u; //explicit v = (V)egd; //explicit u = (U)egd; //implicit array V[] va = null; EG<dynamic>[] egda = va; // explicit array va = (V[])egda; } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0160ERR_UnreachableCatch_TypeParameter_Dynamic2() { string source = @" using System; public class EG<T> : Exception { } public abstract class A<T> { public abstract void M<U>() where U : T; } public class B<V> : A<EG<dynamic>> where V : EG<object> { public override void M<U>() { try { Goo(); } catch (EG<object>) { } catch (V) { } catch (U) { } } void Goo() { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (22,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "V").WithArguments("EG<object>"), // (25,16): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('EG<object>') Diagnostic(ErrorCode.ERR_UnreachableCatch, "U").WithArguments("EG<object>")); } [Fact] public void CS0161ERR_ReturnExpected() { var text = @" public class Test { public static int Main() // CS0161 { int i = 10; if (i < 10) { return i; } else { // uncomment the following line to resolve // return 1; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnExpected, Line = 4, Column = 22 } }); } [Fact] public void CS0163ERR_SwitchFallThrough() { var text = @" public class MyClass { public static void Main() { int i = 0; switch (i) // CS0163 { case 1: i++; // uncomment one of the following lines to resolve // return; // break; // goto case 3; case 2: i++; return; case 3: i = 0; return; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SwitchFallThrough, Line = 10, Column = 10 } }); } [Fact] public void CS0165ERR_UseDefViolation01() { var text = @" class MyClass { public int i; } class MyClass2 { public static void Main(string [] args) { int i, j; if (args[0] == ""test"") { i = 0; } /* // to resolve, either initialize the variables when declared // or provide for logic to initialize them, as follows: else { i = 1; } */ j = i; // CS0165, i might be uninitialized MyClass myClass; myClass.i = 0; // CS0165 // use new as follows // MyClass myClass = new MyClass(); // myClass.i = 0; i = j; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 26, Column = 11 } , new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolation, Line = 29, Column = 7 }}); } [Fact] public void CS0165ERR_UseDefViolation02() { CreateCompilation( @"class C { static void M(int m) { int v; for (int i = 0; i < m; ++i) { v = 0; } M(v); int w; for (; ; ) { w = 0; break; } M(w); for (int x; x < 1; ++x) { } for (int y; m < 1; ++y) { } for (int z; ; ) { M(z); } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "v").WithArguments("v").WithLocation(10, 11), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(18, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(21, 30), Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(26, 15)); } [Fact] public void CS0165ERR_UseDefViolation03() { CreateCompilation( @"class C { static int F() { return 0; } static void M0() { int a, b, c, d; for (a = 1; (b = F()) < 2; c = 3) { d = 4; } if (a == 0) { } if (b == 0) { } if (c == 0) { } // Use of unassigned 'c' if (d == 0) { } // Use of unassigned 'd' } static void M1() { int x, y; for (x = 0; (y = x) < 10; ) { } if (y == 0) { } // no error } static void M2() { int x, y; for (x = 0; x < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M3() { int x, y; for (x = 0; x < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M4() { int x, y; for (y = x; (x = 0) < 10; ) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M5() { int x, y; for (; (x = 0) < 10; y = x) { } if (y == 0) { } // Use of unassigned 'y' } static void M6() { int x, y; for (; (x = 0) < 10; ) { y = x; } if (y == 0) { } // Use of unassigned 'y' } static void M7() { int x, y; for (y = x; F() < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M8() { int x, y; for (; (y = x) < 10; x = 0) { } // Use of unassigned 'x' if (y == 0) { } // no error } static void M9() { int x, y; for (; F() < 10; x = 0) { y = x; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M10() { int x, y; for (y = x; F() < 10; ) { x = 0; } // Use of unassigned 'x' if (y == 0) { } // no error } static void M11() { int x, y; for (; F() < 10; y = x) { x = 0; } if (y == 0) { } // Use of unassigned 'y' } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(13, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(14, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(26, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(32, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(37, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(44, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(50, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(55, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(61, 21), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(67, 39), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(68, 13), Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(73, 18), Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(80, 13)); } [Fact] public void CS0165ERR_UseDefViolation04() { CreateCompilation( @"class C { static int M() { int x, y, z; try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } return (x + y + z); } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(19, 21)); } [Fact] public void CS0165ERR_UseDefViolation05() { // This is a "negative" test case; we should *not* be producing a "use of unassigned // local variable" error here. In an earlier revision we were doing so because we were // losing the information about the first argument being "out" when the bad call node // was created. Later flow analysis then did not know that "x" need not be assigned // before it was used, and we'd produce a wrong error. CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { int x = N(out x, 123); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "N").WithArguments("N", "2")); } [WorkItem(540860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540860")] [Fact] public void CS0165ERR_UseDefViolation06() { // Should not generate "unassigned local variable" for struct. CreateCompilation( @"struct S { public void M() { } } class C { void M() { S s; s.M(); } }") .VerifyDiagnostics(); } [Fact] public void CS0165ERR_UseDefViolation07() { // Make sure flow analysis is hooked up for indexers CreateCompilation( @"struct S { public int this[int x] { get { return 0; } } } class C { public int this[int x] { get { return 0; } } } class Test { static void Main() { int unassigned1; int unassigned2; int sink; C c; sink = c[1]; //CS0165 c = new C(); sink = c[1]; //fine sink = c[unassigned1]; //CS0165 S s; sink = s[1]; //fine - struct with no fields s = new S(); sink = s[1]; //fine sink = s[unassigned2]; //CS0165 } }") .VerifyDiagnostics( // (18,16): error CS0165: Use of unassigned local variable 'c' Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c"), // (22,18): error CS0165: Use of unassigned local variable 'unassigned1' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned1").WithArguments("unassigned1"), // (29,18): error CS0165: Use of unassigned local variable 'unassigned2' Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned2").WithArguments("unassigned2")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0170ERR_UseDefViolationField() { var text = @" public struct error { public int i; } public class MyClass { public static void Main() { error e; // uncomment the next line to resolve this error // e.i = 0; System.Console.WriteLine( e.i ); // CS0170 because //e.i was never assigned } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationField, Line = 14, Column = 33 } }); } [Fact] public void CS0171ERR_UnassignedThis() { var text = @" struct MyStruct { MyStruct(int initField) // CS0171 { // i = initField; // uncomment this line to resolve this error } public int i; } class MyClass { public static void Main() { MyStruct aStruct = new MyStruct(); } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,4): error CS0171: Field 'MyStruct.i' must be fully assigned before control is returned to the caller // MyStruct(int initField) // CS0171 Diagnostic(ErrorCode.ERR_UnassignedThis, "MyStruct").WithArguments("MyStruct.i"), // (15,16): warning CS0219: The variable 'aStruct' is assigned but its value is never used // MyStruct aStruct = new MyStruct(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "aStruct").WithArguments("aStruct"), // (8,15): warning CS0649: Field 'MyStruct.i' is never assigned to, and will always have its default value 0 // public int i; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i").WithArguments("MyStruct.i", "0") ); } [Fact] public void FieldAssignedInReferencedConstructor() { var text = @"struct S { private readonly object _x; S(object o) { _x = o; } S(object x, object y) : this(x ?? y) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics(); // No CS0171 for S._x } [Fact()] public void CS0172ERR_AmbigQM() { var text = @" public class Square { public class Circle { public static implicit operator Circle(Square aa) { return null; } public static implicit operator Square(Circle aa) { return null; } } public static void Main() { Circle aa = new Circle(); Square ii = new Square(); var o1 = (1 == 1) ? aa : ii; // CS0172 object o2 = (1 == 1) ? aa : ii; // CS8652 } }"; CreateCompilation(text, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (21,16): error CS0172: Type of conditional expression cannot be determined because 'Square.Circle' and 'Square' implicitly convert to one another // var o1 = (1 == 1) ? aa : ii; // CS0172 Diagnostic(ErrorCode.ERR_AmbigQM, "(1 == 1) ? aa : ii").WithArguments("Square.Circle", "Square").WithLocation(21, 16), // (22,19): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between 'Square.Circle' and 'Square'. To use a target-typed conversion, upgrade to language version 9.0 or greater. // object o2 = (1 == 1) ? aa : ii; // CS8652 Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, "(1 == 1) ? aa : ii").WithArguments("8.0", "Square.Circle", "Square", "9.0").WithLocation(22, 19) ); } [Fact] public void CS0173ERR_InvalidQM() { var text = @" public class C {} public class A {} public class MyClass { public static void F(bool b) { A a = new A(); C c = new C(); var o = b ? a : c; // CS0173 } public static void Main() { F(true); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,15): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C' // var o = b ? a : c; // CS0173 Diagnostic(ErrorCode.ERR_InvalidQM, "b ? a : c").WithArguments("A", "C").WithLocation(11, 15) ); } [WorkItem(528331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528331")] [Fact] public void CS0173ERR_InvalidQM_FuncCall() { var text = @" class Program { static void Main(string[] args) { var s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1); } }"; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "s = true ? System.Console.WriteLine(0) : System.Console.WriteLine(1)").WithArguments("void").WithLocation(6, 13)); } [Fact] public void CS0173ERR_InvalidQM_GeneralType() { var text = @" class Program { static void Main(string[] args) { A<string> a = new A<string>(); A<int> b = new A<int>(); var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert } } class A<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A<string>' and 'A<int>' // var o = 1 > 2 ? a : b; // Invalid, Can't implicit convert Diagnostic(ErrorCode.ERR_InvalidQM, "1 > 2 ? a : b").WithArguments("A<string>", "A<int>").WithLocation(8, 17) ); } [WorkItem(540902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540902")] [Fact] public void CS0173ERR_InvalidQM_foreach() { var text = @" public class Test { public static void Main() { S[] x = null; foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY { } C[] y= null; foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY { } } } struct S { } class C { } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'S[]' and 'int' // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "true ? x : 1").WithArguments("S[]", "int"), // (7,20): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (S x in true ? x : 1) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), // (11,25): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'C[]' // foreach (C c in false ? 1 : y) // Dev10: CS0173 ONLY Diagnostic(ErrorCode.ERR_InvalidQM, "false ? 1 : y").WithArguments("int", "C[]") ); } // /// Scenarios? // [Fact] // public void CS0174ERR_NoBaseClass() // { // var text = @" // "; // CreateCompilationWithMscorlib(text).VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoBaseClass, "?")); // } [WorkItem(543360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543360")] [Fact()] public void CS0175ERR_BaseIllegal() { var text = @" using System; class Base { public int TestInt = 0; } class MyClass : Base { public void BaseTest() { Console.WriteLine(base); // CS0175 base = 9; // CS0175 } } "; CreateCompilation(text).VerifyDiagnostics( // (11,27): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(12, 27), // (12,9): error CS0175: Use of keyword 'base' is not valid in this context Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(13, 9) ); } [WorkItem(528624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528624")] [Fact()] public void CS0175ERR_BaseIllegal_02() { var text = @" using System.Collections.Generic; class MyClass : List<int> { public void BaseTest() { var x = from i in base select i; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,27): error CS0175: Use of keyword 'base' is not valid in this context // var x = from i in base select i; Diagnostic(ErrorCode.ERR_BaseIllegal, "base") ); } [Fact] public void CS0176ERR_ObjectProhibited01() { var source = @" class A { class B { static void Method() { } void M() { this.Method(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,13): error CS0176: Member 'A.B.Method()' cannot be accessed with an instance reference; qualify it with a type name instead // this.Method(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Method").WithArguments("A.B.Method()").WithLocation(9, 13) ); } [Fact] public void CS0176ERR_ObjectProhibited02() { var source = @" class C { static object field; static object Property { get; set; } void M(C c) { Property = field; // no error C.Property = C.field; // no error this.field = this.Property; c.Property = c.field; } } "; CreateCompilation(source).VerifyDiagnostics( // (9,9): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.field").WithArguments("C.field"), // (9,22): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // this.field = this.Property; Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Property").WithArguments("C.Property"), // (10,9): error CS0176: Member 'C.Property' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.Property").WithArguments("C.Property"), // (10,22): error CS0176: Member 'C.field' cannot be accessed with an instance reference; qualify it with a type name instead // c.Property = c.field; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.field").WithArguments("C.field") ); } [Fact] public void CS0176ERR_ObjectProhibited03() { var source = @"class A { internal static object F; } class B<T> where T : A { static void M(T t) { object q = t.F; t.ReferenceEquals(q, null); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,20): error CS0176: Member 'A.F' cannot be accessed with an instance reference; qualify it with a type name instead // object q = t.F; Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.F").WithArguments("A.F").WithLocation(9, 20), // (10,9): error CS0176: Member 'object.ReferenceEquals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // t.ReferenceEquals(q, null); Diagnostic(ErrorCode.ERR_ObjectProhibited, "t.ReferenceEquals").WithArguments("object.ReferenceEquals(object, object)").WithLocation(10, 9), // (3,28): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // internal static object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null").WithLocation(3, 28)); } [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited04() { var source = @" public delegate void D(); class Test { public event D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics( // (9,9): error CS0176: Member 'Delegate.CreateDelegate(Type, object, string)' cannot be accessed with an instance reference; qualify it with a type name instead // D.CreateDelegate(null, null, null); // CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "D.CreateDelegate").WithArguments("System.Delegate.CreateDelegate(System.Type, object, string)").WithLocation(9, 9) ); } // Identical to CS0176ERR_ObjectProhibited04, but with event keyword removed (i.e. field instead of field-like event). [WorkItem(543361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543361")] [Fact] public void CS0176ERR_ObjectProhibited05() { var source = @" public delegate void D(); class Test { public D D; public void TestIdenticalEventName() { D.CreateDelegate(null, null, null); // CS0176 } } "; CreateCompilation(source).VerifyDiagnostics( // (5,14): warning CS0649: Field 'Test.D' is never assigned to, and will always have its default value null // public D D; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "D").WithArguments("Test.D", "null") ); } [Fact] public void CS0177ERR_ParamUnassigned01() { var text = @"class C { static void M(out int x, out int y, out int z) { try { x = 0; y = 1; } catch (System.Exception) { x = 1; } finally { z = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("y").WithLocation(3, 17)); } [WorkItem(528243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528243")] [Fact] public void CS0177ERR_ParamUnassigned02() { var text = @"class C { static bool P { get { return false; } } static object M(out object x) { if (P) { object o = P ? M(out x) : null; return o; } return P ? null : M(out x); } }"; CreateCompilation(text).VerifyDiagnostics( // (9,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return o; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return o;").WithArguments("x").WithLocation(9, 13), // (11,9): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method // return P ? null : M(out x); Diagnostic(ErrorCode.ERR_ParamUnassigned, "return P ? null : M(out x);").WithArguments("x").WithLocation(11, 9)); } [Fact] public void CS0185ERR_LockNeedsReference() { var text = @" public class MainClass { public static void Main () { lock (1) // CS0185 // try the following lines instead // MainClass x = new MainClass(); // lock(x) { } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LockNeedsReference, Line = 6, Column = 15 } }); } [Fact] public void CS0186ERR_NullNotValid() { var text = @" using System.Collections; class MyClass { static void Main() { // Each of the following lines generates CS0186: foreach (int i in null) { } // CS0186 foreach (int i in (IEnumerable)null) { }; // CS0186 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 9, Column = 27 } , new ErrorDescription { Code = (int)ErrorCode.ERR_NullNotValid, Line = 10, Column = 27 }}); } [Fact] public void CS0186ERR_NullNotValid02() { var text = @" public class Test { public static void Main(string[] args) { foreach (var x in default(int[])) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NullNotValid, "default(int[])")); } [WorkItem(540983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540983")] [Fact] public void CS0188ERR_UseDefViolationThis() { var text = @" namespace MyNamespace { class MyClass { struct S { public int a; void Goo() { } S(int i) { // a = i; Goo(); // CS0188 } } public static void Main() { } } }"; CreateCompilation(text). VerifyDiagnostics( // (17,17): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // Goo(); // CS0188 Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Goo").WithArguments("this"), // (8,24): warning CS0649: Field 'MyNamespace.MyClass.S.a' is never assigned to, and will always have its default value 0 // public int a; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("MyNamespace.MyClass.S.a", "0")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ImplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. Diagnostic(ErrorCode.ERR_LambdaInIsAs, "F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "F").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533"), WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] public void CS0188ERR_UseDefViolationThis_MethodGroupInIsOperator_ExplicitReceiver() { string source = @" using System; struct S { int value; public S(int v) { var b1 = this.F is Action; value = v; } void F() { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,18): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_LambdaInIsAs, "this.F is Action").WithLocation(10, 18), // (10,18): error CS0188: The 'this' object cannot be used before all of its fields are assigned to // var b1 = this.F is Action; Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ImplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { /*this.*/ Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,19): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "Add").WithArguments("this")); } [Fact, WorkItem(579533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579533")] public void CS0188ERR_UseDefViolationThis_ExplicitReceiverInDynamic() { string source = @" using System; struct S { dynamic value; public S(dynamic d) { this.Add(d); throw new NotImplementedException(); } void Add(int value) { this.value += value; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (10,9): error CS0188: The 'this' object cannot be used before all of its fields are assigned to Diagnostic(ErrorCode.ERR_UseDefViolationThis, "this").WithArguments("this")); } [Fact] public void CS0190ERR_ArgsInvalid() { string source = @" using System; public class C { static void M(__arglist) { ArgIterator ai = new ArgIterator(__arglist); } static void Main() { M(__arglist); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (11,7): error CS0190: The __arglist construct is valid only within a variable argument method // M(__arglist); Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda01() { // Note that the native compiler does *not* produce an error when you illegally // use __arglist inside a lambda, oddly enough. Roslyn does. string source = @" using System; using System.Linq; public class C { delegate int D(RuntimeArgumentHandle r); static void M(__arglist) { D f = null; f = x=>f(__arglist); f = delegate { return f(__arglist); }; var q = from x in new int[10] select f(__arglist); } static void Main() { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (10,14): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = x=>f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (11,29): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // f = delegate { return f(__arglist); }; Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle"), // (12,44): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // var q = from x in new int[10] select f(__arglist); Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle") ); } [Fact] public void CS4013ERR_SpecialByRefInLambda02() { string source = @" using System; public class C { static void M(__arglist) { RuntimeArgumentHandle h = __arglist; Action action = ()=> { RuntimeArgumentHandle h2 = h; // Bad use of h ArgIterator args1 = new ArgIterator(h); // Bad use of h RuntimeArgumentHandle h3 = h2; // no error; does not create field ArgIterator args2 = new ArgIterator(h2); // no error; does not create field }; } static void Main() { } }"; CreateCompilationWithMscorlib45(source).VerifyEmitDiagnostics( // (10,34): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // RuntimeArgumentHandle h2 = h; // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle"), // (11,43): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // ArgIterator args1 = new ArgIterator(h); // Bad use of h Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h").WithArguments("System.RuntimeArgumentHandle")); } [Fact] public void CS4013ERR_SpecialByRefInLambda03() { string source = @" using System; using System.Collections.Generic; public class C { static void N(RuntimeArgumentHandle x) {} static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field { N(h1); yield return 1; RuntimeArgumentHandle h2 = default(RuntimeArgumentHandle); yield return 2; N(h2); // Error: hoisted to field yield return 3; RuntimeArgumentHandle h3 = default(RuntimeArgumentHandle); N(h3); // No error; we don't need to hoist this one to a field } static void Main() { } }"; CreateCompilation(source).Emit(new System.IO.MemoryStream()).Diagnostics .Verify( // (7,51): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // static IEnumerable<int> M(RuntimeArgumentHandle h1) // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h1").WithArguments("System.RuntimeArgumentHandle"), // (13,7): error CS4013: Instance of type 'System.RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method // N(h2); // Error: hoisted to field Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "h2").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(538008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538008")] public void CS0191ERR_AssgReadonly() { var source = @"class MyClass { public readonly int TestInt = 6; // OK to assign to readonly field in declaration public MyClass() { TestInt = 11; // OK to assign to readonly field in constructor TestInt = 12; // OK to assign to readonly field multiple times in constructor this.TestInt = 13; // OK to assign with explicit this receiver MyClass t = this; t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this } public void TestReadOnly() { TestInt = 19; // CS0191 } public static void Main() { } } class MyDerived : MyClass { MyDerived() { TestInt = 15; // CS0191 - not in declaring class } } "; CreateCompilation(source).VerifyDiagnostics( // (28,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 15; // CS0191 - not in declaring class Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(28, 9), // (11,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // t.TestInt = 14; // CS0191 - we can't be sure that the receiver is this Diagnostic(ErrorCode.ERR_AssgReadonly, "t.TestInt").WithLocation(11, 9), // (16,9): error CS0191: A readonly field cannot be assigned to (except in the constructor of the class in which the field is defined or a variable initializer)) // TestInt = 19; // CS0191 Diagnostic(ErrorCode.ERR_AssgReadonly, "TestInt").WithLocation(16, 9)); } [WorkItem(538009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538009")] [Fact] public void CS0192ERR_RefReadonly() { var text = @" class MyClass { public readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // OK } public void PassReadOnlyRef() { TestMethod(ref TestInt); // CS0192 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonly, Line = 17, Column = 24 } }); } [Fact] public void CS0193ERR_PtrExpected() { var text = @" using System; public struct Age { public int AgeYears; public int AgeMonths; public int AgeDays; } public class MyClass { public static void SetAge(ref Age anAge, int years, int months, int days) { anAge->Months = 3; // CS0193, anAge is not a pointer // try the following line instead // anAge.AgeMonths = 3; } public static void Main() { Age MyAge = new Age(); Console.WriteLine(MyAge.AgeMonths); SetAge(ref MyAge, 22, 4, 15); Console.WriteLine(MyAge.AgeMonths); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PtrExpected, Line = 15, Column = 7 } }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void CS0196ERR_PtrIndexSingle() { var text = @" unsafe public class MyClass { public static void Main () { int *i = null; int j = 0; j = i[1,2]; // CS0196 // try the following line instead // j = i[1]; } }"; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,11): error CS0196: A pointer must be indexed by only one value // j = i[1,2]; // CS0196 Diagnostic(ErrorCode.ERR_PtrIndexSingle, "i[1,2]")); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[1,2]", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1,2]') Children(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32*, IsInvalid) (Syntax: 'i') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1,2]') Children(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "); } [Fact] public void CS0198ERR_AssgReadonlyStatic() { var text = @" public class MyClass { public static readonly int TestInt = 6; static MyClass() { TestInt = 7; TestInt = 8; MyClass.TestInt = 7; } public MyClass() { TestInt = 11; // CS0198, constructor is not static and readonly field is } private void InstanceMethod() { TestInt = 12; // CS0198 } private void StaticMethod() { TestInt = 13; // CS0198 } public static void Main() { } } class MyDerived : MyClass { static MyDerived() { MyClass.TestInt = 14; // CS0198, not in declaring class } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 15, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 20, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 25, Column = 8 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonlyStatic, Line = 37, Column = 9 }, }); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() { var text = @"public static class Goo<T> { static Goo() { Goo<int>.X = 1; Goo<int>.Y = 2; Goo<T>.Y = 3; } public static readonly int X; public static int Y { get; } }"; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (5,9): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) // Goo<int>.X = 1; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, "Goo<int>.X").WithLocation(5, 9), // (6,9): error CS0200: Property or indexer 'Goo<int>.Y' cannot be assigned to -- it is read only // Goo<int>.Y = 2; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "Goo<int>.Y").WithArguments("Goo<int>.Y").WithLocation(6, 9) ); } [Fact, WorkItem(990, "https://github.com/dotnet/roslyn/issues/990")] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation02() { var text = @"using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine(Goo<long>.x); Console.WriteLine(Goo<int>.x); Console.WriteLine(Goo<string>.x); Console.WriteLine(Goo<int>.x); } } public static class Goo<T> { static Goo() { Console.WriteLine(""initializing for "" + typeof(T)); Goo<int>.x = typeof(T).Name; } public static readonly string x; }"; var expectedOutput = @"initializing for System.Int64 initializing for System.Int32 Int64 initializing for System.String String "; // Although we accept this nasty code, it will not verify. CompileAndVerify(text, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void CS0199ERR_RefReadonlyStatic() { var text = @" class MyClass { public static readonly int TestInt = 6; static void TestMethod(ref int testInt) { testInt = 0; } MyClass() { TestMethod(ref TestInt); // CS0199, TestInt is static } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_RefReadonlyStatic, Line = 13, Column = 24 } }); } [Fact] public void CS0200ERR_AssgReadonlyProp01() { var source = @"abstract class A { internal static A P { get { return null; } } internal object Q { get; set; } public abstract object R { get; } } class B : A { public override object R { get { return null; } } } class Program { static void M(B b) { B.P.Q = null; B.P = null; // CS0200 b.R = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (16,9): error CS0200: Property or indexer 'A.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "B.P").WithArguments("A.P").WithLocation(16, 9), // (17,9): error CS0200: Property or indexer 'B.R' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.R").WithArguments("B.R").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp02() { var source = @"class A { public virtual A P { get; set; } public A Q { get { return null; } } } class B : A { public override A P { get { return null; } } } class Program { static void M(B b) { b.P = null; b.Q = null; // CS0200 b.Q.P = null; b.P.Q = null; // CS0200 } }"; CreateCompilation(source).VerifyDiagnostics( // (15,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.Q").WithArguments("A.Q").WithLocation(15, 9), // (17,9): error CS0200: Property or indexer 'A.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P.Q").WithArguments("A.Q").WithLocation(17, 9)); } [Fact] public void CS0200ERR_AssgReadonlyProp03() { var source = @"class C { static int P { get { return 0; } } int Q { get { return 0; } } static void M(C c) { ++P; ++c.Q; } }"; CreateCompilation(source).VerifyDiagnostics( // (7,11): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(7, 11), // (8,11): error CS0200: Property or indexer 'C.Q' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.Q").WithArguments("C.Q").WithLocation(8, 11)); } [Fact] public void CS0200ERR_AssgReadonlyProp04() { var source = @"class C { object P { get { P = null; return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,22): error CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(3, 22)); } [Fact] public void CS0200ERR_AssgReadonlyProp05() { CreateCompilation( @"class C { int this[int x] { get { return x; } } void M(int b) { this[0] = b; this[1]++; this[2] += 1; } }") .VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[0]").WithArguments("C.this[int]"), // (7,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[1]").WithArguments("C.this[int]"), // (8,9): error CS0200: Property or indexer 'C.this[int]' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "this[2]").WithArguments("C.this[int]")); } [Fact] public void CS0200ERR_AssgReadonlyProp06() { var source1 = @"public class A { public virtual object P { get { return null; } private set { } } } public class B : A { public override object P { get { return null; } } }"; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics(); var compilationVerifier = CompileAndVerify(compilation1); var reference1 = MetadataReference.CreateFromImage(compilationVerifier.EmittedAssemblyData); var source2 = @"class C { static void M(B b) { var o = b.P; b.P = o; } }"; var compilation2 = CreateCompilation(source2, references: new[] { reference1 }); compilation2.VerifyDiagnostics( // (6,9): error CS0200: Property or indexer 'B.P' cannot be assigned to -- it is read only Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "b.P").WithArguments("B.P").WithLocation(6, 9)); } [Fact] public void CS0201ERR_IllegalStatement1() { var text = @" public class MyList<T> { public void Add(T x) { int i = 0; if ( (object)x == null) { checked(i++); // CS0201 // OK checked { i++; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (9,10): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement Diagnostic(ErrorCode.ERR_IllegalStatement, "checked(i++)")); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2() { var text = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; CreateCompilation(text, parseOptions: TestOptions.Regular.WithTuplesFeature()).VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact, WorkItem(536863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536863")] public void CS0201ERR_IllegalStatement2WithCSharp6() { var test = @" class A { public static int Main() { (a) => a; (a, b) => { }; int x = 0; int y = 0; x + y; x == 1; } }"; var comp = CreateCompilation(new[] { Parse(test, options: TestOptions.Regular6) }, new MetadataReference[] { }); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a) => a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (a, b) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(7, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x + y").WithLocation(9, 9), // (9,16): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x + y; x == 1; Diagnostic(ErrorCode.ERR_IllegalStatement, "x == 1").WithLocation(9, 16), // (4,23): error CS0161: 'A.Main()': not all code paths return a value // public static int Main() Diagnostic(ErrorCode.ERR_ReturnExpected, "Main").WithArguments("A.Main()").WithLocation(4, 23) ); } [Fact] public void CS0202ERR_BadGetEnumerator() { var text = @" public class C1 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public static implicit operator C1 (int c1) { return 0; } } public class C2 { public int Current { get { return 0; } } public bool MoveNext () { return false; } public C1[] GetEnumerator () { return null; } } public class MainClass { public static void Main () { C2 c2 = new C2(); foreach (C1 x in c2) // CS0202 { System.Console.WriteLine(x.Current); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadGetEnumerator, Line = 50, Column = 24 } }); } // [Fact()] // public void CS0204ERR_TooManyLocals() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_TooManyLocals, Line = 8, Column = 13 } } // ); // } [Fact()] public void CS0205ERR_AbstractBaseCall() { var text = @"abstract class A { abstract public void M(); abstract protected object P { get; } } class B : A { public override void M() { base.M(); // CS0205 object o = base.P; // CS0205 } protected override object P { get { return null; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 10, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractBaseCall, Line = 11, Column = 20 }); } [Fact] public void CS0205ERR_AbstractBaseCall_Override() { var text = @" public class Base1 { public virtual long Property1 { get { return 0; } set { } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } void test1() { Property1 += 1; } } public class Derived : Base2 { public override long Property1 { get { return 1; } set { } } void test2() { base.Property1++; base.Property1 = 2; long x = base.Property1; } } "; CreateCompilation(text).VerifyDiagnostics( // (19,9): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1"), // (21,18): error CS0205: Cannot call an abstract base member: 'Base2.Property1' Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property1").WithArguments("Base2.Property1")); } [Fact] public void CS0206ERR_RefProperty() { var text = @"class C { static int P { get; set; } object Q { get; set; } static void M(ref int i) { } static void M(out object o) { o = null; } void M() { M(ref P); // CS0206 M(out this.Q); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "P").WithArguments("C.P"), // (15,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this.Q").WithArguments("C.Q")); } [Fact] public void CS0206ERR_RefProperty_Indexers() { var text = @"class C { int this[int x] { get { return x; } set { } } static void R(ref int i) { } static void O(out int o) { o = 0; } void M() { R(ref this[0]); // CS0206 O(out this[0]); // CS0206 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]"), // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter Diagnostic(ErrorCode.ERR_RefProperty, "this[0]").WithArguments("C.this[int]")); } [Fact] public void CS0208ERR_ManagedAddr01() { var text = @" class myClass { public int a = 98; } struct myProblemStruct { string s; float f; } struct myGoodStruct { int i; float f; } public class MyClass { unsafe public static void Main() { // myClass is a class, a managed type. myClass s = new myClass(); myClass* s2 = &s; // CS0208 // The struct contains a string, a managed type. int i = sizeof(myProblemStruct); //CS0208 // The struct contains only value types. i = sizeof(myGoodStruct); //OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (25,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "myClass*").WithArguments("myClass"), // (25,23): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myClass') // myClass* s2 = &s; // CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("myClass"), // (28,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('myProblemStruct') // int i = sizeof(myProblemStruct); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(myProblemStruct)").WithArguments("myProblemStruct"), // (9,12): warning CS0169: The field 'myProblemStruct.s' is never used // string s; Diagnostic(ErrorCode.WRN_UnreferencedField, "s").WithArguments("myProblemStruct.s"), // (10,11): warning CS0169: The field 'myProblemStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myProblemStruct.f"), // (15,9): warning CS0169: The field 'myGoodStruct.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("myGoodStruct.i"), // (16,11): warning CS0169: The field 'myGoodStruct.f' is never used // float f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("myGoodStruct.f")); } [Fact] public void CS0208ERR_ManagedAddr02() { var source = @"enum E { } delegate void D(); struct S { } interface I { } unsafe class C { object* _object; void* _void; bool* _bool; char* _char; sbyte* _sbyte; byte* _byte; short* _short; ushort* _ushort; int* _int; uint* _uint; long* _long; ulong* _ulong; decimal* _decimal; float* _float; double* _double; string* _string; System.IntPtr* _intptr; System.UIntPtr* _uintptr; int** _intptr2; int?* _nullable; dynamic* _dynamic; E* e; D* d; S* s; I* i; C* c; }"; CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll) .GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error) .Verify( // (22,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // string* _string; Diagnostic(ErrorCode.ERR_ManagedAddr, "_string").WithArguments("string").WithLocation(22, 13), // (27,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // dynamic* _dynamic; Diagnostic(ErrorCode.ERR_ManagedAddr, "_dynamic").WithArguments("dynamic").WithLocation(27, 14), // (29,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('D') // D* d; Diagnostic(ErrorCode.ERR_ManagedAddr, "d").WithArguments("D").WithLocation(29, 8), // (31,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('I') // I* i; Diagnostic(ErrorCode.ERR_ManagedAddr, "i").WithArguments("I").WithLocation(31, 8), // (32,8): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // C* c; Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("C").WithLocation(32, 8), // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // object* _object; Diagnostic(ErrorCode.ERR_ManagedAddr, "_object").WithArguments("object").WithLocation(7, 13)); } [Fact] public void CS0209ERR_BadFixedInitType() { var text = @" class Point { public int x, y; } public class MyClass { unsafe public static void Main() { Point pt = new Point(); fixed (int i) // CS0209 { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,18): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_BadFixedInitType, "i"), // (13,18): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (int i) // CS0209 Diagnostic(ErrorCode.ERR_FixedMustInit, "i"), // (4,15): warning CS0649: Field 'Point.x' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "x").WithArguments("Point.x", "0"), // (4,18): warning CS0649: Field 'Point.y' is never assigned to, and will always have its default value 0 // public int x, y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "y").WithArguments("Point.y", "0")); } [Fact] public void CS0210ERR_FixedMustInit() { var text = @" using System.IO; class Test { static void Main() { using (StreamWriter w) // CS0210 { w.WriteLine(""Hello there""); } using (StreamWriter x, y) // CS0210, CS0210 { } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter w) // CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "w").WithLocation(7, 27), // (12,27): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(12, 27), // (12,30): error CS0210: You must provide an initializer in a fixed or using statement declaration // using (StreamWriter x, y) // CS0210, CS0210 Diagnostic(ErrorCode.ERR_FixedMustInit, "y").WithLocation(12, 30), // (9,10): error CS0165: Use of unassigned local variable 'w' // w.WriteLine("Hello there"); Diagnostic(ErrorCode.ERR_UseDefViolation, "w").WithArguments("w").WithLocation(9, 10) ); } [Fact] public void CS0211ERR_InvalidAddrOp() { var text = @" public class MyClass { unsafe public void M() { int a = 0, b = 0; int *i = &(a + b); // CS0211, the addition of two local variables // try the following line instead // int *i = &a; } public static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0211: Cannot take the address of the given expression // int *i = &(a + b); // CS0211, the addition of two local variables Diagnostic(ErrorCode.ERR_InvalidAddrOp, "a + b")); } [Fact] public void CS0212ERR_FixedNeeded() { var text = @" public class A { public int iField = 5; unsafe public void M() { A a = new A(); int* ptr = &a.iField; // CS0212 } // OK unsafe public void M2() { A a = new A(); fixed (int* ptr = &a.iField) {} } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* ptr = &a.iField; // CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&a.iField")); } [Fact] public void CS0213ERR_FixedNotNeeded() { var text = @" public class MyClass { unsafe public static void Main() { int i = 45; fixed (int *j = &i) { } // CS0213 // try the following line instead // int* j = &i; int[] a = new int[] {1,2,3}; fixed (int *b = a) { fixed (int *c = b) { } // CS0213 // try the following line instead // int *c = b; } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,23): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int *j = &i) { } // CS0213 Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&i").WithLocation(7, 23), // (14,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int *c = b) { } // CS0213 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "b").WithLocation(14, 26)); } [Fact] public void CS0217ERR_BadBoolOp() { // Note that the wording of this error message has changed. var text = @" public class MyClass { public static bool operator true (MyClass f) { return false; } public static bool operator false (MyClass f) { return false; } public static int operator & (MyClass f1, MyClass f2) { return 0; } public static void Main() { MyClass f = new MyClass(); int i = f && f; // CS0217 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,15): error CS0217: In order to be applicable as a short circuit operator a user-defined logical operator ('MyClass.operator &(MyClass, MyClass)') must have the same return type and parameter types // int i = f && f; // CS0217 Diagnostic(ErrorCode.ERR_BadBoolOp, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)")); } // CS0220 ERR_CheckedOverflow - see ConstantTests [Fact] public void CS0221ERR_ConstOutOfRangeChecked01() { string text = @"class MyClass { static void F(int x) { } static void M() { F((int)0xFFFFFFFF); // CS0221 F(unchecked((int)uint.MaxValue)); F(checked((int)(uint.MaxValue - 1))); // CS0221 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0221: Constant value '4294967295' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)0xFFFFFFFF").WithArguments("4294967295", "int"), // (8,19): error CS0221: Constant value '4294967294' cannot be converted to a 'int' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)(uint.MaxValue - 1)").WithArguments("4294967294", "int")); } [Fact] public void CS0221ERR_ConstOutOfRangeChecked02() { string text = @"enum E : byte { A, B = 0xfe, C } class C { const int F = (int)(E.C + 1); // CS0221 const int G = (int)unchecked(1 + E.C); const int H = (int)checked(E.A - 1); // CS0221 } "; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0031: Constant value '256' cannot be converted to a 'E' Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.C + 1").WithArguments("256", "E"), // (6,32): error CS0221: Constant value '-1' cannot be converted to a 'E' (use 'unchecked' syntax to override) Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "E.A - 1").WithArguments("-1", "E")); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact(Skip = "1119609")] public void CS0221ERR_ConstOutOfRangeChecked03() { var text = @"public class MyClass { decimal x1 = (decimal)double.PositiveInfinity; //CS0221 decimal x2 = (decimal)double.NegativeInfinity; //CS0221 decimal x3 = (decimal)double.NaN; //CS0221 decimal x4 = (decimal)double.MaxValue; //CS0221 public static void Main() {} } "; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0031: Constant value 'Infinity' cannot be converted to a 'decimal' // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.PositiveInfinity").WithArguments("Infinity", "decimal"), // (4,18): error CS0031: Constant value '-Infinity' cannot be converted to a 'decimal' // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NegativeInfinity").WithArguments("-Infinity", "decimal"), // (5,18): error CS0031: Constant value 'NaN' cannot be converted to a 'decimal' // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.NaN").WithArguments("NaN", "decimal"), // (6,18): error CS0031: Constant value '1.79769313486232E+308' cannot be converted to a 'decimal' // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.ERR_ConstOutOfRange, "(decimal)double.MaxValue").WithArguments("1.79769313486232E+308", "decimal"), // (3,13): warning CS0414: The field 'MyClass.x1' is assigned but its value is never used // decimal x1 = (decimal)double.PositiveInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x1").WithArguments("MyClass.x1"), // (4,13): warning CS0414: The field 'MyClass.x2' is assigned but its value is never used // decimal x2 = (decimal)double.NegativeInfinity; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x2").WithArguments("MyClass.x2"), // (5,13): warning CS0414: The field 'MyClass.x3' is assigned but its value is never used // decimal x3 = (decimal)double.NaN; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x3").WithArguments("MyClass.x3"), // (6,13): warning CS0414: The field 'MyClass.x4' is assigned but its value is never used // decimal x4 = (decimal)double.MaxValue; //CS0221 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x4").WithArguments("MyClass.x4")); } [Fact] public void CS0226ERR_IllegalArglist() { var text = @" public class C { public static int Main () { __arglist(1,""This is a string""); // CS0226 return 0; } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_IllegalArglist, @"__arglist(1,""This is a string"")")); } // [Fact()] // public void CS0228ERR_NoAccessibleMember() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoAccessibleMember, Line = 31, Column = 17 } } // ); // } [Fact] public void CS0229ERR_AmbigMember() { var text = @" interface IList { int Count { get; set; } void Counter(); } interface Icounter { double Count { get; set; } } interface IListCounter : IList , Icounter {} class MyClass { void Test(IListCounter x) { x.Count = 1; // CS0229 // Try one of the following lines instead: // ((IList)x).Count = 1; // or // ((Icounter)x).Count = 1; } public static void Main() {} } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigMember, Line = 28, Column = 11 } }); } [Fact] public void CS0233ERR_SizeofUnsafe() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct S { public int a; } public class MyClass { public static void Main() { S myS = new S(); Console.WriteLine(sizeof(S)); // CS0233 // Try the following line instead: // Console.WriteLine(Marshal.SizeOf(myS)); } } "; CreateCompilation(text).VerifyDiagnostics( // (16,27): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // Console.WriteLine(sizeof(S)); // CS0233 Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S"), // (15,11): warning CS0219: The variable 'myS' is assigned but its value is never used // S myS = new S(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "myS").WithArguments("myS")); } [Fact] public void CS0236ERR_FieldInitRefNonstatic() { var text = @" public class MyClass { int[] instanceArray; static int[] staticArray; static int staticField = 1; const int constField = 1; int a; int b = 1; int c = b; //CS0236 int d = this.b; //CS0027 int e = InstanceMethod(); //CS0236 int f = this.InstanceMethod(); //CS0027 int g = StaticMethod(); int h = MyClass.StaticMethod(); int i = GenericInstanceMethod<int>(1); //CS0236 int j = this.GenericInstanceMethod<int>(1); //CS0027 int k = GenericStaticMethod<int>(1); int l = MyClass.GenericStaticMethod<int>(1); int m = InstanceProperty; //CS0236 int n = this.InstanceProperty; //CS0027 int o = StaticProperty; int p = MyClass.StaticProperty; int q = instanceArray[0]; //CS0236 int r = this.instanceArray[0]; //CS0027 int s = staticArray[0]; int t = MyClass.staticArray[0]; int u = staticField; int v = MyClass.staticField; int w = constField; int x = MyClass.constField; MyClass() { a = b; } int InstanceMethod() { return a; } static int StaticMethod() { return 1; } T GenericInstanceMethod<T>(T t) { return t; } static T GenericStaticMethod<T>(T t) { return t; } int InstanceProperty { get { return a; } } static int StaticProperty { get { return 1; } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.b' // int c = b; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "b").WithArguments("MyClass.b").WithLocation(12, 13), // (13,13): error CS0027: Keyword 'this' is not available in the current context // int d = this.b; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(13, 13), // (14,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceMethod()' // int e = InstanceMethod(); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceMethod").WithArguments("MyClass.InstanceMethod()").WithLocation(14, 13), // (15,13): error CS0027: Keyword 'this' is not available in the current context // int f = this.InstanceMethod(); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(15, 13), // (18,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.GenericInstanceMethod<int>(int)' // int i = GenericInstanceMethod<int>(1); //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "GenericInstanceMethod<int>").WithArguments("MyClass.GenericInstanceMethod<int>(int)").WithLocation(18, 13), // (19,13): error CS0027: Keyword 'this' is not available in the current context // int j = this.GenericInstanceMethod<int>(1); //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(19, 13), // (22,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.InstanceProperty' // int m = InstanceProperty; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "InstanceProperty").WithArguments("MyClass.InstanceProperty").WithLocation(22, 13), // (23,13): error CS0027: Keyword 'this' is not available in the current context // int n = this.InstanceProperty; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(23, 13), // (26,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MyClass.instanceArray' // int q = instanceArray[0]; //CS0236 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "instanceArray").WithArguments("MyClass.instanceArray").WithLocation(26, 13), // (27,13): error CS0027: Keyword 'this' is not available in the current context // int r = this.instanceArray[0]; //CS0027 Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(27, 13), // (4,11): warning CS0649: Field 'MyClass.instanceArray' is never assigned to, and will always have its default value null // int[] instanceArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "instanceArray").WithArguments("MyClass.instanceArray", "null").WithLocation(4, 11), // (5,18): warning CS0649: Field 'MyClass.staticArray' is never assigned to, and will always have its default value null // static int[] staticArray; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "staticArray").WithArguments("MyClass.staticArray", "null").WithLocation(5, 18), // (33,9): warning CS0414: The field 'MyClass.x' is assigned but its value is never used // int x = MyClass.constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("MyClass.x").WithLocation(33, 9), // (32,9): warning CS0414: The field 'MyClass.w' is assigned but its value is never used // int w = constField; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "w").WithArguments("MyClass.w").WithLocation(32, 9) ); } [Fact] public void CS0236ERR_FieldInitRefNonstaticMethodGroups() { var text = @" delegate void F(); public class MyClass { F a = Static; F b = MyClass.Static; F c = Static<int>; F d = MyClass.Static<int>; F e = Instance; F f = this.Instance; F g = Instance<int>; F h = this.Instance<int>; static void Static() { } static void Static<T>() { } void Instance() { } void Instance<T>() { } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib( text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 9, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 10, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_FieldInitRefNonstatic, Line = 11, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ThisInBadContext, Line = 12, Column = 11 }, }); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstaticProperty() { CreateCompilation( @" enum ProtectionLevel { Privacy = 0 } class F { const ProtectionLevel p = ProtectionLevel.Privacy; // CS0236 int ProtectionLevel { get { return 0; } } } ") .VerifyDiagnostics( // (9,29): error CS0236: A field initializer cannot reference the non-static field, method, or property 'F.ProtectionLevel' // const ProtectionLevel p = ProtectionLevel.Privacy; // CS0120 Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "ProtectionLevel").WithArguments("F.ProtectionLevel")); } [WorkItem(541501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541501")] [Fact] public void CS0236ERR_FieldInitRefNonstatic_ObjectInitializer() { CreateCompilation( @" public class Goo { public int i; public string s; } public class MemberInitializerTest { private int i =10; private string s = ""abc""; private Goo f = new Goo{i = i, s = s}; public static void Main() { } } ") .VerifyDiagnostics( // (12,33): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.i' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "i").WithArguments("MemberInitializerTest.i").WithLocation(12, 33), // (12,40): error CS0236: A field initializer cannot reference the non-static field, method, or property 'MemberInitializerTest.s' // private Goo f = new Goo{i = i, s = s}; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "s").WithArguments("MemberInitializerTest.s").WithLocation(12, 40)); } [Fact] public void CS0236ERR_FieldInitRefNonstatic_AnotherInitializer() { CreateCompilation( @" class TestClass { int P1 { get; } int y = (P1 = 123); int y1 { get; } = (P1 = 123); static void Main() { } } ") .VerifyDiagnostics( // (6,14): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(6, 14), // (7,24): error CS0236: A field initializer cannot reference the non-static field, method, or property 'TestClass.P1' // int y1 { get; } = (P1 = 123); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "P1").WithArguments("TestClass.P1").WithLocation(7, 24) ); } [Fact] public void CS0242ERR_VoidError() { var text = @" class TestClass { public unsafe void Test() { void* p = null; p++; //CS0242 p += 2; //CS0242 void* q = p + 1; //CS0242 long diff = q - p; //CS0242 var v = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,9): error CS0242: The operation in question is undefined on void pointers // p++; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p++"), // (8,9): error CS0242: The operation in question is undefined on void pointers // p += 2; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p += 2"), // (9,19): error CS0242: The operation in question is undefined on void pointers // void* q = p + 1; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "p + 1"), // (10,21): error CS0242: The operation in question is undefined on void pointers // long diff = q - p; //CS0242 Diagnostic(ErrorCode.ERR_VoidError, "q - p"), // (11,17): error CS0242: The operation in question is undefined on void pointers // var v = *p; Diagnostic(ErrorCode.ERR_VoidError, "*p")); } [Fact] public void CS0244ERR_PointerInAsOrIs() { var text = @" class UnsafeTest { unsafe static void SquarePtrParam (int* p) { bool b = p is object; // CS0244 p is pointer } unsafe public static void Main() { int i = 5; SquarePtrParam (&i); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,16): error CS0244: Neither 'is' nor 'as' is valid on pointer types // bool b = p is object; // CS0244 p is pointer Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "p is object")); } [Fact] public void CS0245ERR_CallingFinalizeDeprecated() { var text = @" class MyClass // : IDisposable { /* public void Dispose() { // cleanup code goes here } */ void m() { this.Finalize(); // CS0245 // this.Dispose(); } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,7): error CS0245: Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. Diagnostic(ErrorCode.ERR_CallingFinalizeDeprecated, "this.Finalize()")); } [WorkItem(540722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540722")] [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { CreateCompilation(@" namespace nms { public class Mine { private static int retval = 5; public static int Main() { try { } catch (e) { } return retval; } }; } ") .VerifyDiagnostics( // (10,20): error CS0246: The type or namespace name 'e' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "e").WithArguments("e")); } [WorkItem(528446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528446")] [Fact] public void CS0246ERR_SingleTypeNameNotFoundNoCS8000() { CreateCompilation(@" class Test { void Main() { var sum = new j(); } } ") .VerifyDiagnostics( // (11,20): error CS0246: The type or namespace name 'j' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "j").WithArguments("j")); } [Fact] public void CS0247ERR_NegativeStackAllocSize() { var text = @" public class MyClass { unsafe public static void Main() { int *p = stackalloc int [-30]; // CS0247 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,32): error CS0247: Cannot use a negative size with stackalloc // int *p = stackalloc int [-30]; // CS0247 Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-30")); } [Fact] public void CS0248ERR_NegativeArraySize() { var text = @" class MyClass { public static void Main() { int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes int[] myArray3 = new int[3000000000u]; // slightly different code path for uint array sizes var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; var myArray5 = new object[-1L] {null}; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,33): error CS0248: Cannot create an array with a negative size // int[] myArray = new int[-3] {1,2,3}; // CS0248, pass a nonnegative number Diagnostic(ErrorCode.ERR_NegativeArraySize, "-3").WithLocation(6, 33), // (7,34): error CS0248: Cannot create an array with a negative size // int[] myArray2 = new int[-5000000000]; // slightly different code path for long array sizes Diagnostic(ErrorCode.ERR_NegativeArraySize, "-5000000000").WithLocation(7, 34), // (9,35): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-2").WithLocation(9, 35), // (9,42): error CS0248: Cannot create an array with a negative size // var myArray4 = new object[-2, 1, -1] {{{null}},{{null}}}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1").WithLocation(9, 42), // (10,35): error CS0248: Cannot create an array with a negative size // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_NegativeArraySize, "-1L").WithLocation(10, 35), // (10,35): error CS0150: A constant value is expected // var myArray5 = new object[-1L] {null}; Diagnostic(ErrorCode.ERR_ConstantExpected, "-1L").WithLocation(10, 35)); } [WorkItem(528912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528912")] [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" class B { } class C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()")); } [Fact] public void CS0254ERR_BadCastInFixed() { var text = @" class Point { public uint x, y; } class FixedTest { unsafe static void SquarePtrParam (int* p) { *p *= *p; } unsafe public static void Main() { Point pt = new Point(); pt.x = 5; pt.y = 6; fixed (int* p = (int*)&pt.x) // CS0254 // try the following line instead // fixed (uint* p = &pt.x) { SquarePtrParam ((int*)p); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (20,23): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = (int*)&pt.x) // CS0254 Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)&pt.x").WithLocation(20, 23)); } [Fact] public void CS0255ERR_StackallocInFinally() { var text = @" unsafe class Test { void M() { try { // Something } finally { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0255ERR_StackallocInCatch() { var text = @" unsafe class Test { void M() { try { // Something } catch { int* fib = stackalloc int[100]; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,24): error CS0255: stackalloc may not be used in a catch or finally block // int* fib = stackalloc int[100]; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[100]").WithLocation(12, 24)); } [Fact] public void CS0266ERR_NoImplicitConvCast01() { var text = @" class MyClass { public static void Main() { object obj = ""MyString""; // Cannot implicitly convert 'object' to 'MyClass' MyClass myClass = obj; // CS0266 // Try this line instead // MyClass c = ( MyClass )obj; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoImplicitConvCast, Line = 8, Column = 27 } }); } [Fact] public void CS0266ERR_NoImplicitConvCast02() { var source = @"class C { const int f = 0L; } "; CreateCompilation(source).VerifyDiagnostics( // (3,19): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // const int f = 0L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "0L").WithArguments("long", "int").WithLocation(3, 19)); } [Fact] public void CS0266ERR_NoImplicitConvCast03() { var source = @"class C { static void M() { const short s = 1L; } } "; CreateCompilation(source).VerifyDiagnostics( // (5,25): error CS0266: Cannot implicitly convert type 'long' to 'short'. An explicit conversion exists (are you missing a cast?) // const short s = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "short").WithLocation(5, 25), // (5,21): warning CS0219: The variable 's' is assigned but its value is never used // const short s = 1L; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(5, 21)); } [Fact] public void CS0266ERR_NoImplicitConvCast04() { var source = @"enum E { A = 1 } class C { E f = 2; // CS0266 E g = E.A; void M() { f = E.A; g = 'c'; // CS0266 } } "; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0266: Cannot implicitly convert type 'int' to 'E'. An explicit conversion exists (are you missing a cast?) // E f = 2; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "2").WithArguments("int", "E").WithLocation(4, 11), // (9,13): error CS0266: Cannot implicitly convert type 'char' to 'E'. An explicit conversion exists (are you missing a cast?) // g = 'c'; // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'c'").WithArguments("char", "E").WithLocation(9, 13), // (4,7): warning CS0414: The field 'C.f' is assigned but its value is never used // E f = 2; // CS0266 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "f").WithArguments("C.f").WithLocation(4, 7), // (5,7): warning CS0414: The field 'C.g' is assigned but its value is never used // E g = E.A; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "g").WithArguments("C.g").WithLocation(5, 7)); } [Fact] public void CS0266ERR_NoImplicitConvCast05() { var source = @"enum E : byte { A = 'a', // CS0266 B = 0xff, } "; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0266: Cannot implicitly convert type 'char' to 'byte'. An explicit conversion exists (are you missing a cast?) // A = 'a', // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "'a'").WithArguments("char", "byte").WithLocation(3, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast06() { var source = @"enum E { A = 1, B = 1L // CS0266 } "; CreateCompilation(source).VerifyDiagnostics( // (4,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // B = 1L // CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(4, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast07() { // No errors var source = "enum E { A, B = A }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast08() { // No errors var source = @"enum E { A = 1, B } enum F { X = E.A + 1, Y } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void CS0266ERR_NoImplicitConvCast09() { var source = @"enum E { A = F.A, B = F.B, C = G.A, D = G.B, } enum F : short { A = 1, B } enum G : long { A = 1, B } "; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // C = G.A, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.A").WithArguments("long", "int").WithLocation(5, 9), // (6,9): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // D = G.B, Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "G.B").WithArguments("long", "int").WithLocation(6, 9)); } [Fact] public void CS0266ERR_NoImplicitConvCast10() { var source = @"class C { public const int F = D.G + 1; } class D { public const int G = E.H + 1; } class E { public const int H = 1L; } "; CreateCompilation(source).VerifyDiagnostics( // (11,26): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // public const int H = 1L; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(11, 26)); } [Fact()] public void CS0266ERR_NoImplicitConvCast11() { string text = @"class Program { static void Main(string[] args) { bool? b = true; int result = b ? 0 : 1; // Compiler error } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b").WithArguments("bool?", "bool")); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast12() { string text = @" class C1 { public static void Main() { var cube = new int[Number.One][]; } } enum Number { One, Two } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0266: Cannot implicitly convert type 'Number' to 'int'. An explicit conversion exists (are you missing a cast?) // var cube = new int[Number.One][]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "Number.One").WithArguments("Number", "int").WithLocation(6, 28)); } [WorkItem(541718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541718")] [Fact] public void CS0266ERR_NoImplicitConvCast13() { string text = @" class C1 { public static void Main() { double x = 5; int[] arr4 = new int[x];// Invalid float y = 5; int[] arr5 = new int[y];// Invalid decimal z = 5; int[] arr6 = new int[z];// Invalid } } "; CreateCompilation(text). VerifyDiagnostics( // (7,30): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr4 = new int[x];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("double", "int").WithLocation(7, 30), // (10,30): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr5 = new int[y];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("float", "int").WithLocation(10, 30), // (13,30): error CS0266: Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?) // int[] arr6 = new int[z];// Invalid Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "z").WithArguments("decimal", "int").WithLocation(13, 30)); } [Fact] public void CS0266ERR_NoImplicitConvCast14() { string source = @" class C { public unsafe void M(int* p, object o) { _ = p[o]; // error with span on 'o' _ = p[0]; // ok } } "; CreateCompilation(source, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // _ = p[o]; // error with span on 'o' Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 15)); } [Fact] public void CS0266ERR_NoImplicitConvCast15() { string source = @" class C { public void M(object o) { int[o] x; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[o]; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[o]").WithLocation(6, 12), // (6,13): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // int[o]; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "int").WithLocation(6, 13), // (6,16): warning CS0168: The variable 'x' is declared but never used // int[o] x; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(6, 16)); } [Fact] public void CS0269ERR_UseDefViolationOut() { var text = @" class C { public static void F(out int i) { try { // Assignment occurs, but compiler can't verify it i = 1; } catch { } int k = i; // CS0269 i = 1; } public static void Main() { int myInt; F(out myInt); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UseDefViolationOut, Line = 15, Column = 17 } }); } [Fact] public void CS0271ERR_InaccessibleGetter01() { var source = @"class C { internal static object P { private get; set; } public C Q { protected get { return null; } set { } } } class P { static void M(C c) { object o = C.P; M(c.Q); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,20): error CS0271: The property or indexer 'C.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "C.P").WithArguments("C.P").WithLocation(10, 20), // (11,11): error CS0271: The property or indexer 'C.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "c.Q").WithArguments("C.Q").WithLocation(11, 11)); } [Fact] public void CS0271ERR_InaccessibleGetter02() { var source = @"class A { public virtual object P { protected get; set; } } class B : A { public override object P { set { } } void M() { object o = P; // no error } } class C { void M(B b) { object o = b.P; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,20): error CS0271: The property or indexer 'B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("B.P").WithLocation(17, 20)); } [Fact] public void CS0271ERR_InaccessibleGetter03() { var source = @"namespace N1 { class A { void M(N2.B b) { object o = b.P; } } } namespace N2 { class B : N1.A { public object P { protected get; set; } } }"; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0271: The property or indexer 'N2.B.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "b.P").WithArguments("N2.B.P").WithLocation(7, 24)); } [Fact] public void CS0271ERR_InaccessibleGetter04() { var source = @"class A { static public object P { protected get; set; } static internal object Q { private get; set; } static void M() { object o = B.Q; // no error o = A.Q; // no error } } class B : A { static void M() { object o = B.P; // no error o = P; // no error o = Q; // CS0271 } } class C { static void M() { object o = B.P; // CS0271 o = A.Q; // CS0271 } }"; CreateCompilation(source).VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "Q").WithArguments("A.Q").WithLocation(17, 13), // (24,20): error CS0271: The property or indexer 'A.P' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "B.P").WithArguments("A.P").WithLocation(24, 20), // (25,13): error CS0271: The property or indexer 'A.Q' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "A.Q").WithArguments("A.Q").WithLocation(25, 13)); } [Fact] public void CS0271ERR_InaccessibleGetter05() { CreateCompilation( @"class A { public object this[int x] { protected get { return null; } set { } } internal object this[string s] { private get { return null; } set { } } void M() { object o = new B()[""hello""]; // no error o = new A()[""hello""]; // no error } } class B : A { void M() { object o = new B()[0]; // no error o = this[0]; // no error o = this[""hello""]; // CS0271 } } class C { void M() { object o = new B()[0]; // CS0271 o = new A()[""hello""]; // CS0271 } }") .VerifyDiagnostics( // (17,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"this[""hello""]").WithArguments("A.this[string]"), // (24,20): error CS0271: The property or indexer 'A.this[int]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, "new B()[0]").WithArguments("A.this[int]"), // (25,13): error CS0271: The property or indexer 'A.this[string]' cannot be used in this context because the get accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleGetter, @"new A()[""hello""]").WithArguments("A.this[string]")); } [Fact] public void CS0272ERR_InaccessibleSetter01() { var source = @"namespace N { class C { internal object P { get; private set; } static public C Q { get { return null; } protected set { } } } class P { static void M(C c) { c.P = c; C.Q = c; } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,13): error CS0272: The property or indexer 'N.C.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "c.P").WithArguments("N.C.P").WithLocation(12, 13), // (13,13): error CS0272: The property or indexer 'N.C.Q' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "C.Q").WithArguments("N.C.Q").WithLocation(13, 13)); } [Fact] public void CS0272ERR_InaccessibleSetter02() { var source = @"namespace N1 { abstract class A { public virtual object P { get; protected set; } } } namespace N2 { class B : N1.A { public override object P { get { return null; } } void M() { P = null; // no error } } } class C { void M(N2.B b) { b.P = null; // CS0272 } }"; CreateCompilation(source).VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.P' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b.P").WithArguments("N2.B.P").WithLocation(23, 9)); } [Fact] public void CS0272ERR_InaccessibleSetter03() { CreateCompilation( @"namespace N1 { abstract class A { public virtual object this[int x] { get { return null; } protected set { } } } } namespace N2 { class B : N1.A { public override object this[int x] { get { return null; } } void M() { this[0] = null; // no error } } } class C { void M(N2.B b) { b[0] = null; // CS0272 } } ") .VerifyDiagnostics( // (23,9): error CS0272: The property or indexer 'N2.B.this[int]' cannot be used in this context because the set accessor is inaccessible Diagnostic(ErrorCode.ERR_InaccessibleSetter, "b[0]").WithArguments("N2.B.this[int]")); } [Fact] public void CS0283ERR_BadConstType() { // Test for both ERR_BadConstType and an error for RHS to ensure // the RHS is not reported multiple times (when calculating the // constant value for the symbol and also when binding). var source = @"struct S { static void M(object o) { const S s = 2; M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0283: The type 'S' cannot be declared const // const S s = 2; Diagnostic(ErrorCode.ERR_BadConstType, "S").WithArguments("S").WithLocation(5, 15), // (5,21): error CS0029: Cannot implicitly convert type 'int' to 'S' // const S s = 2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "S").WithLocation(5, 21)); } [Fact] public void CS0304ERR_NoNewTyvar01() { var source = @"struct S<T, U> where U : new() { void M<V>() { object o; o = new T(); o = new U(); o = new V(); } } class C<T, U> where T : struct where U : class { void M<V, W>() where V : struct where W : class, new() { object o; o = new T(); o = new U(); o = new V(); o = new W(); } }"; CreateCompilation(source).VerifyDiagnostics( // (6,13): error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T()").WithArguments("T").WithLocation(6, 13), // (8, 13): error CS0304: Cannot create an instance of the variable type 'V' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new V()").WithArguments("V").WithLocation(8, 13), // (21,13): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(21, 13)); } [WorkItem(542377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542377")] [Fact] public void CS0304ERR_NoNewTyvar02() { var source = @"struct S { } class C { } abstract class A<T> { public abstract U F<U>() where U : T; } class B1 : A<int> { public override U F<U>() { return new U(); } } class B2 : A<S> { public override U F<U>() { return new U(); } } class B3 : A<C> { public override U F<U>() { return new U(); } }"; CreateCompilation(source).VerifyDiagnostics( // (17,39): error CS0304: Cannot create an instance of the variable type 'U' because it does not have the new() constraint Diagnostic(ErrorCode.ERR_NoNewTyvar, "new U()").WithArguments("U").WithLocation(17, 39)); } [WorkItem(542547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542547")] [Fact] public void CS0305ERR_BadArity() { var text = @" public class NormalType { public static int M1<T1>(T1 p1, T1 p2) { return 0; } public static int Main() { M1<int, >(10, 11); return -1; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,17): error CS1031: Type expected Diagnostic(ErrorCode.ERR_TypeExpected, ">"), // (7,9): error CS0305: Using the generic method 'NormalType.M1<T1>(T1, T1)' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M1<int, >").WithArguments("NormalType.M1<T1>(T1, T1)", "method", "1")); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied01() { var text = @"class A<T> { } class B { private B() { } } delegate void D(); enum E { } struct S { } class C<T, U> where T : new() { static void M<V>() where V : new() { M<A<int>>(); M<B>(); M<D>(); M<E>(); M<object>(); M<int>(); M<S>(); M<T>(); M<U>(); M<B, B>(); M<T, U>(); M<T, V>(); M<T[]>(); M<dynamic>(); } static void M<V, W>() where V : new() where W : new() { } }"; CreateCompilation(text).VerifyDiagnostics( // (14,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<T, U>.M<V>()", "V", "B").WithLocation(14, 9), // (15,9): error CS0310: 'D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<D>").WithArguments("C<T, U>.M<V>()", "V", "D").WithLocation(15, 9), // (21,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<U>").WithArguments("C<T, U>.M<V>()", "V", "U").WithLocation(21, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "V", "B").WithLocation(22, 9), // (22,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B, B>").WithArguments("C<T, U>.M<V, W>()", "W", "B").WithLocation(22, 9), // (23,9): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'W' in the generic type or method 'C<T, U>.M<V, W>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T, U>").WithArguments("C<T, U>.M<V, W>()", "W", "U").WithLocation(23, 9), // (25,9): error CS0310: 'T[]' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>()' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<T[]>").WithArguments("C<T, U>.M<V>()", "V", "T[]").WithLocation(25, 9)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied02() { var text = @"class A { } class B { internal B() { } } class C<T> where T : new() { internal static void M<U>() where U : new() { } internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> } delegate T D<T>() where T : new(); static class E { internal static void M<T>(this object o) where T : new() { } internal static void F<T>(D<T> d) where T : new() { } } class F<T, U> where U : new() { } abstract class G { } class H : G { } interface I { } struct S { private S(object o) { } static void M() { C<A>.M<A>(); C<A>.M<B>(); C<B>.M<A>(); C<B>.M<B>(); C<G>.M<H>(); C<H>.M<G>(); C<I>.M<S>(); E.F(S.F<A>); E.F(S.F<B>); E.F(S.F<C<A>>); E.F(S.F<C<B>>); var o = new object(); o.M<A>(); o.M<B>(); o = new F<A, B>(); o = new F<B, A>(); } static T F<T>() { return default(T); } }"; // Note that none of these errors except the first one are reported by the native compiler, because // it does not report additional errors after an error is found in a formal parameter of a method. CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (9,36): error CS0310: 'U' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' // internal static void E<U>(D<U> d) { } // Error: missing constraint on E<U> to satisfy constraint on D<U> Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "d").WithArguments("D<T>", "T", "U").WithLocation(9, 36), // (29,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<A>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<A>.M<U>()", "U", "B").WithLocation(29, 14), // (30,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(30, 11), // (31,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(31, 11), // (31,14): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<B>.M<U>()' // C<B>.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("C<B>.M<U>()", "U", "B").WithLocation(31, 14), // (32,11): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<G>.M<H>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "G").WithArguments("C<T>", "T", "G").WithLocation(32, 11), // (33,14): error CS0310: 'G' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<H>.M<U>()' // C<H>.M<G>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<G>").WithArguments("C<H>.M<U>()", "U", "G").WithLocation(33, 14), // (34,11): error CS0310: 'I' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<I>.M<S>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "I").WithArguments("C<T>", "T", "I").WithLocation(34, 11), // (36,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.F<T>(D<T>)' // E.F(S.F<B>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("E.F<T>(D<T>)", "T", "B").WithLocation(36, 11), // (38,19): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("C<T>", "T", "B").WithLocation(38, 19), // This invocation of E.F(S.F<C<B>>) is an extremely interesting one. // First off, obviously the type argument for S.F is prima facie wrong, so we give an error for that above. // But what about the overload resolution problem in error recovery? Even though the argument is bad we still // might want to try to get an overload resolution result. Thus we must infer a type for T in E.F<T>(D<T>). // We must do overload resolution on an invocation S.F<C<B>>(). Overload resolution succeeds; it has no reason // to fail. (Overload resolution would fail if a formal parameter type of S.F<C<B>>() did not satisfy one of its // constraints, but there are no formal parameters. Also, there are no constraints at all on T in S.F<T>.) // // Thus T in D<T> is inferred to be C<B>, and thus T in E.F<T> is inferred to be C<B>. // // Now we check to see whether E.F<C<B>>(D<C<B>>) is applicable. It is inapplicable because // B fails to meet the constraints of T in C<T>. (C<B> does not fail to meet the constraints // of T in D<T> because C<B> has a public default parameterless ctor.) // // Therefore E.F<C.B>(S.F<C<B>>) fails overload resolution. Why? Because B is not valid for T in C<T>. // (We cannot say that the constraints on T in E.F<T> is unmet because again, C<B> meets the // constraint; it has a ctor.) So that is the error we report. // // This is arguably a "cascading" error; we have already reported an error for C<B> when the // argument was bound. Normally we avoid reporting "cascading" errors in overload resolution by // saying that an erroneous argument is implicitly convertible to any formal parameter type; // thus we avoid an erroneous expression from causing overload resolution to make every // candidate method inapplicable. (Though it might cause overload resolution to fail by making // every candidate method applicable, causing an ambiguity!) But the overload resolution // error here is not caused by an argument *conversion* in the first place; the overload // resolution error is caused because *the deduced formal parameter type is illegal.* // // We might want to put some gear in place to suppress this cascading error. It is not // entirely clear what that machinery might look like. // (38,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // E.F(S.F<C<B>>); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "F").WithArguments("C<T>", "T", "B").WithLocation(38, 11), // (41,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'E.M<T>(object)' // o.M<B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<B>").WithArguments("E.M<T>(object)", "T", "B").WithLocation(41, 11), // (42,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'F<T, U>' // o = new F<A, B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("F<T, U>", "U", "B").WithLocation(42, 22)); } [Fact] public void CS0310ERR_NewConstraintNotSatisfied03() { var text = @"class A { } class B { private B() { } } class C<T, U> where U : struct { internal static void M<V>(V v) where V : new() { } void M() { A a = default(A); M(a); a.E(); B b = default(B); M(b); b.E(); T t = default(T); M(t); t.E(); U u1 = default(U); M(u1); u1.E(); U? u2 = null; M(u2); u2.E(); } } static class S { internal static void E<T>(this T t) where T : new() { } }"; CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (15,9): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(b); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "B").WithLocation(15, 9), // (16,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // b.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "B").WithLocation(16, 11), // (18,9): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'V' in the generic type or method 'C<T, U>.M<V>(V)' // M(t); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M").WithArguments("C<T, U>.M<V>(V)", "V", "T").WithLocation(18, 9), // (19,11): error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'S.E<T>(T)' // t.E(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "E").WithArguments("S.E<T>(T)", "T", "T").WithLocation(19, 11) ); } /// <summary> /// Constraint errors within aliases. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied04() { var text = @"using NA = N.A; using NB = N.B; using CA = N.C<N.A>; using CB = N.C<N.B>; namespace N { using CAD = C<N.A>.D; using CBD = C<N.B>.D; class A { } // public (default) .ctor class B { private B() { } } // private .ctor class C<T> where T : new() { internal static void M<U>() where U : new() { } internal class D { private D() { } // private .ctor internal static void M<U>() where U : new() { } } } class E { static void M() { C<N.A>.M<N.B>(); C<NB>.M<NA>(); C<C<N.A>.D>.M<N.A>(); C<N.A>.D.M<N.B>(); C<N.B>.D.M<N.A>(); CA.M<N.B>(); CB.M<N.A>(); CAD.M<N.B>(); CBD.M<N.A>(); C<CAD>.M<N.A>(); C<CBD>.M<N.A>(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (4,7): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CB = N.C<N.B>; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CB").WithArguments("N.C<T>", "T", "N.B").WithLocation(4, 7), // (8,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // using CBD = C<N.B>.D; Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.B").WithLocation(8, 11), // (24,20): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // C<N.A>.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(24, 20), // (25,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<NB>.M<NA>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "NB").WithArguments("N.C<T>", "T", "N.B").WithLocation(25, 15), // (26,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<C<N.A>.D>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C<N.A>.D").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(26, 15), // (27,22): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // C<N.A>.D.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(27, 22), // (28,15): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<N.B>.D.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "N.B").WithArguments("N.C<T>", "T", "N.B").WithLocation(28, 15), // (29,16): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.M<U>()' // CA.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.M<U>()", "U", "N.B").WithLocation(29, 16), // (31,17): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'U' in the generic type or method 'C<A>.D.M<U>()' // CAD.M<N.B>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "M<N.B>").WithArguments("N.C<N.A>.D.M<U>()", "U", "N.B").WithLocation(31, 17), // (33,15): error CS0310: 'C<A>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CAD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CAD").WithArguments("N.C<T>", "T", "N.C<N.A>.D").WithLocation(33, 15), // (34,15): error CS0310: 'C<B>.D' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C<T>' // C<CBD>.M<N.A>(); Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "CBD").WithArguments("N.C<T>", "T", "N.C<N.B>.D").WithLocation(34, 15)); } /// <summary> /// Constructors with optional and params args /// should not be considered parameterless. /// </summary> [Fact] public void CS0310ERR_NewConstraintNotSatisfied05() { var text = @"class A { public A() { } } class B { public B(object o = null) { } } class C { public C(params object[] args) { } } class D<T> where T : new() { static void M() { D<A>.M(); D<B>.M(); D<C>.M(); } }"; CreateCompilation(text).VerifyDiagnostics( // (18,11): error CS0310: 'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "B").WithArguments("D<T>", "T", "B").WithLocation(18, 11), // (19,11): error CS0310: 'C' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'D<T>' Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "C").WithArguments("D<T>", "T", "C").WithLocation(19, 11)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType01() { var source = @"class A { } class B { } class C<T> where T : A { } class D { static void M<T>() where T : A { } static void M() { object o = new C<B>(); M<B>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("C<T>", "A", "T", "B").WithLocation(9, 26), // (10,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'D.M<T>()'. There is no implicit reference conversion from 'B' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<B>").WithArguments("D.M<T>()", "A", "T", "B").WithLocation(10, 9)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<T, V> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0311: The type 'V' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'V' to 'T'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "V").WithArguments("C<T, U>", "T", "U", "V").WithLocation(3, 12)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType03() { var source = @"interface I<T> where T : I<I<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0311: The type 'I<T>' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. There is no implicit reference conversion from 'I<T>' to 'I<I<I<T>>>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T").WithArguments("I<T>", "I<I<I<T>>>", "T", "I<T>").WithLocation(1, 13)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType04() { var source = @"interface IA<T> { } interface IB<T> where T : IA<T> { } class C<T1, T2, T3> where T1 : IB<object[]> where T2 : IB<T2> where T3 : IB<IB<T3>[]>, IA<T3> { }"; CreateCompilation(source).VerifyDiagnostics( // (3,9): error CS0311: The type 'object[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'object[]' to 'IA<object[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T1").WithArguments("IB<T>", "IA<object[]>", "T", "object[]").WithLocation(3, 9), // (3,13): error CS0311: The type 'T2' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T2' to 'IA<T2>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T2").WithArguments("IB<T>", "IA<T2>", "T", "T2").WithLocation(3, 13), // (3,17): error CS0311: The type 'IB<T3>[]' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no implicit reference conversion from 'IB<T3>[]' to 'IA<IB<T3>[]>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "T3").WithArguments("IB<T>", "IA<IB<T3>[]>", "T", "IB<T3>[]").WithLocation(3, 17)); } [Fact] public void CS0311ERR_GenericConstraintNotSatisfiedRefType05() { var source = @"namespace N { class C<T, U> where U : T { static object F() { return null; } static object G<V>() where V : T { return null; } static void M() { object o; o = C<int, object>.F(); o = N.C<int, int>.G<string>(); } } }"; CreateCompilation(source).VerifyDiagnostics( // (16,24): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no implicit reference conversion from 'object' to 'int'. // o = C<int, object>.F(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "object").WithArguments("N.C<T, U>", "int", "U", "object").WithLocation(16, 24), // (17,31): error CS0311: The type 'string' cannot be used as type parameter 'V' in the generic type or method 'C<int, int>.G<V>()'. There is no implicit reference conversion from 'string' to 'int'. // o = N.C<int, int>.G<string>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "G<string>").WithArguments("N.C<int, int>.G<V>()", "int", "V", "string").WithLocation(17, 31)); } [Fact] public void CS0312ERR_GenericConstraintNotSatisfiedNullableEnum() { var source = @"class A<T, U> where T : U { } class B<T> { static void M<U>() where U : T { } static void M() { object o = new A<int?, int>(); B<int>.M<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,26): error CS0312: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. The nullable type 'int?' does not satisfy the constraint of 'int'. // object o = new A<int?, int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "int?").WithArguments("A<T, U>", "int", "T", "int?").WithLocation(7, 26), // (8,16): error CS0312: The type 'int?' cannot be used as type parameter 'U' in the generic type or method 'B<int>.M<U>()'. The nullable type 'int?' does not satisfy the constraint of 'int'. // B<int>.M<int?>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum, "M<int?>").WithArguments("B<int>.M<U>()", "int", "U", "int?").WithLocation(8, 16)); } [Fact] public void CS0313ERR_GenericConstraintNotSatisfiedNullableInterface() { var source = @"interface I { } struct S : I { } class A<T> where T : I { } class B { static void M<T>() where T : I { } static void M() { object o = new A<S?>(); M<S?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "S?").WithArguments("A<T>", "I", "T", "S?").WithLocation(9, 26), // (10,9): error CS0313: The type 'S?' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. The nullable type 'S?' does not satisfy the constraint of 'I'. Nullable types can not satisfy any interface constraints. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface, "M<S?>").WithArguments("B.M<T>()", "I", "T", "S?").WithLocation(10, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar01() { var source = @"class A { } class B<T> where T : A { } class C<T> where T : struct { static void M<U>() where U : A { } static void M() { object o = new B<T>(); M<T>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,26): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("B<T>", "A", "T", "T").WithLocation(8, 26), // (9,9): error CS0314: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'C<T>.M<U>()'. There is no boxing conversion or type parameter conversion from 'T' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M<T>").WithArguments("C<T>.M<U>()", "A", "U", "T").WithLocation(9, 9)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar02() { var source = @"class C<T, U> where U : T { void M<V>() where V : C<V, U> { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0314: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'C<T, U>'. There is no boxing conversion or type parameter conversion from 'U' to 'V'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "V").WithArguments("C<T, U>", "V", "U", "U").WithLocation(3, 12)); } [Fact] public void CS0314ERR_GenericConstraintNotSatisfiedTyVar03() { var source = @"interface IA<T> where T : IB<T> { } interface IB<T> where T : IA<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (1,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IB<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IA<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IB<T>", "IA<T>", "T", "T").WithLocation(1, 14), // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'IA<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'IB<T>'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("IA<T>", "IB<T>", "T", "T").WithLocation(2, 14)); } [Fact] public void CS0315ERR_GenericConstraintNotSatisfiedValType() { var source = @"class A { } class B<T> where T : A { } struct S { } class C { static void M<T, U>() where U : A { } static void M() { object o = new B<S>(); M<int, double>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,26): error CS0315: The type 'S' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. There is no boxing conversion from 'S' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "S").WithArguments("B<T>", "A", "T", "S").WithLocation(9, 26), // (10,9): error CS0315: The type 'double?' cannot be used as type parameter 'U' in the generic type or method 'C.M<T, U>()'. There is no boxing conversion from 'double?' to 'A'. Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int, double>").WithArguments("C.M<T, U>()", "A", "U", "double").WithLocation(10, 9)); } [Fact] public void CS0316ERR_DuplicateGeneratedName() { var text = @" public class Test { public int this[int value] // CS0316 { get { return 1; } set { } } public int this[char @value] // CS0316 { get { return 1; } set { } } public int this[string value] // no error since no setter { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,26): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[char @value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "@value").WithArguments("value").WithLocation(10, 26), // (4,25): error CS0316: The parameter name 'value' conflicts with an automatically-generated parameter name // public int this[int value] // CS0316 Diagnostic(ErrorCode.ERR_DuplicateGeneratedName, "value").WithArguments("value").WithLocation(4, 25)); } [Fact] public void CS0403ERR_TypeVarCantBeNull() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M() { T1 t1 = null; T2 t2 = null; T3 t3 = null; T4 t4 = null; T5 t5 = null; T6 t6 = null; T7 t7 = null; } static T1 F1() { return null; } static T2 F2() { return null; } static T3 F3() { return null; } static T4 F4() { return null; } static T5 F5() { return null; } static T6 F6() { return null; } static T7 F7() { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,17): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // T1 t1 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (15,17): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // T3 t3 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (16,17): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // T4 t4 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (17,17): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // T5 t5 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (19,17): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // T7 t7 = null; Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7"), // (14,12): warning CS0219: The variable 't2' is assigned but its value is never used // T2 t2 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t2").WithArguments("t2"), // (18,12): warning CS0219: The variable 't6' is assigned but its value is never used // T6 t6 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t6").WithArguments("t6"), // (21,29): error CS0403: Cannot convert null to type parameter 'T1' because it could be a non-nullable value type. Consider using 'default(T1)' instead. // static T1 F1() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T1"), // (23,29): error CS0403: Cannot convert null to type parameter 'T3' because it could be a non-nullable value type. Consider using 'default(T3)' instead. // static T3 F3() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T3"), // (24,29): error CS0403: Cannot convert null to type parameter 'T4' because it could be a non-nullable value type. Consider using 'default(T4)' instead. // static T4 F4() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T4"), // (25,29): error CS0403: Cannot convert null to type parameter 'T5' because it could be a non-nullable value type. Consider using 'default(T5)' instead. // static T5 F5() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T5"), // (27,29): error CS0403: Cannot convert null to type parameter 'T7' because it could be a non-nullable value type. Consider using 'default(T7)' instead. // static T7 F7() { return null; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T7") ); } [WorkItem(539901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539901")] [Fact] public void CS0407ERR_BadRetType_01() { var text = @" public delegate int MyDelegate(); class C { MyDelegate d; public C() { d = new MyDelegate(F); // OK: F returns int d = new MyDelegate(G); // CS0407 - G doesn't return int } public int F() { return 1; } public void G() { } public static void Main() { C c1 = new C(); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); CreateCompilation(text).VerifyDiagnostics( // (11,28): error CS0407: 'void C.G()' has the wrong return type // d = new MyDelegate(G); // CS0407 - G doesn't return int Diagnostic(ErrorCode.ERR_BadRetType, "G").WithArguments("C.G()", "void").WithLocation(11, 28) ); } [WorkItem(925899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925899")] [Fact] public void CS0407ERR_BadRetType_02() { var text = @" using System; class C { public static void Main() { var oo = new Func<object, object>(x => 1); var os = new Func<object, string>(oo); var ss = new Func<string, string>(oo); } } "; CreateCompilation(text, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (10,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object System.Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); CreateCompilation(text).VerifyDiagnostics( // (10,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var os = new Func<object, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(10, 43), // (11,43): error CS0407: 'object Func<object, object>.Invoke(object)' has the wrong return type // var ss = new Func<string, string>(oo); Diagnostic(ErrorCode.ERR_BadRetType, "oo").WithArguments("System.Func<object, object>.Invoke(object)", "object").WithLocation(11, 43) ); } [WorkItem(539924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539924")] [Fact] public void CS0407ERR_BadRetType_03() { var text = @" delegate DerivedClass MyDerivedDelegate(DerivedClass x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base""); return x; } } public class DerivedClass : BaseClass { public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDerivedDelegate goo1 = null; goo1 += BaseClass.DelegatedMethod; goo1 += DerivedClass.DelegatedMethod; goo1(new DerivedClass()); } } "; CreateCompilation(text).VerifyDiagnostics( // (21,17): error CS0407: 'BaseClass BaseClass.DelegatedMethod(BaseClass)' has the wrong return type Diagnostic(ErrorCode.ERR_BadRetType, "BaseClass.DelegatedMethod").WithArguments("BaseClass.DelegatedMethod(BaseClass)", "BaseClass")); } [WorkItem(3401, "DevDiv_Projects/Roslyn")] [Fact] public void CS0411ERR_CantInferMethTypeArgs01() { var text = @" class C { public void F<T>(T t) where T : C { } public static void Main() { C c = new C(); c.F(null); // CS0411 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantInferMethTypeArgs, Line = 11, Column = 11 } }); } [WorkItem(2099, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2099")] [Fact(Skip = "529560")] public void CS0411ERR_CantInferMethTypeArgs02() { var text = @" public class MemberInitializerTest { delegate void D<T>(); public static void GenericMethod<T>() { } public static void Run() { var genD = (D<int>)GenericMethod; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,20): error CS0030: The type arguments for method 'MemberInitializerTest.GenericMethod<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var genD = (D<int>)GenericMethod; Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "(D<int>)GenericMethod").WithArguments("MemberInitializerTest.GenericMethod<T>()") ); } [Fact] public void CS0412ERR_LocalSameNameAsTypeParam() { var text = @" using System; class C { // Parameter name is the same as method type parameter name public void G<T>(int T) // CS0412 { } public void F<T>() { // Method local variable name is the same as method type // parameter name double T = 0.0; // CS0412 Console.WriteLine(T); } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 7, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_LocalSameNameAsTypeParam, Line = 14, Column = 16 } }); } [Fact] public void CS0413ERR_AsWithTypeVar() { var source = @"interface I { } class A { } class B<T1, T2, T3, T4, T5, T6, T7> where T2 : class where T3 : struct where T4 : new() where T5 : I where T6 : A where T7 : T1 { static void M(object o) { o = o as T1; o = o as T2; o = o as T3; o = o as T4; o = o as T5; o = o as T6; o = o as T7; } }"; CreateCompilation(source).VerifyDiagnostics( // (13,13): error CS0413: The type parameter 'T1' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T1").WithArguments("T1").WithLocation(13, 13), // (15,13): error CS0413: The type parameter 'T3' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T3").WithArguments("T3").WithLocation(15, 13), // (16,13): error CS0413: The type parameter 'T4' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T4").WithArguments("T4").WithLocation(16, 13), // (17,13): error CS0413: The type parameter 'T5' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T5").WithArguments("T5").WithLocation(17, 13), // (19,13): error CS0413: The type parameter 'T7' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint Diagnostic(ErrorCode.ERR_AsWithTypeVar, "o as T7").WithArguments("T7").WithLocation(19, 13)); } [Fact] public void CS0417ERR_NewTyvarWithArgs01() { var source = @"struct S<T> where T : new() { T F(object o) { return new T(o); } U G<U, V>(object o) where U : new() where V : struct { return new U(new V(o)); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(o)").WithArguments("T").WithLocation(5, 16), // (11,16): error CS0417: 'U': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new U(new V(o))").WithArguments("U").WithLocation(11, 16), // (11,22): error CS0417: 'V': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new V(o)").WithArguments("V").WithLocation(11, 22)); } [Fact] public void CS0417ERR_NewTyvarWithArgs02() { var source = @"class C { public C() { } public C(object o) { } static void M<T>() where T : C, new() { new T(); new T(null); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(null)").WithArguments("T").WithLocation(8, 9)); } [Fact] public void CS0428ERR_MethGrpToNonDel() { var text = @" namespace ConsoleApplication1 { class Program { delegate int Del1(); delegate object Del2(); static void Main(string[] args) { ExampleClass ec = new ExampleClass(); int i = ec.Method1; Del1 d1 = ec.Method1; i = ec.Method1(); ec = ExampleClass.Method2; Del2 d2 = ExampleClass.Method2; ec = ExampleClass.Method2(); } } public class ExampleClass { public int Method1() { return 1; } public static ExampleClass Method2() { return null; } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MethGrpToNonDel, Line = 15, Column = 31 }}); } [Fact, WorkItem(528649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528649")] public void CS0431ERR_ColColWithTypeAlias() { var text = @" using AliasC = C; class C { public class Goo { } } class Test { class C { } static int Main() { AliasC::Goo goo = new AliasC::Goo(); return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC"), Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "AliasC").WithArguments("AliasC")); } [WorkItem(3402, "DevDiv_Projects/Roslyn")] [Fact] public void CS0445ERR_UnboxNotLValue() { var text = @" namespace ConsoleApplication1 { // CS0445.CS class UnboxingTest { public static void Main() { Point p = new Point(); p.x = 1; p.y = 5; object obj = p; // Generates CS0445: ((Point)obj).x = 2; } } public struct Point { public int x; public int y; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnboxNotLValue, Line = 15, Column = 13 } }); } [Fact] public void CS0446ERR_AnonMethGrpInForEach() { var text = @" class Tester { static void Main() { int[] intArray = new int[5]; foreach (int i in M) { } // CS0446 } static void M() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethGrpInForEach, Line = 7, Column = 27 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0452_GenericConstraintError_HasHigherPriorityThanMethodOverloadError() { var code = @" class Code { void GenericMethod<T>(int i) where T: class => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<int>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (9,9): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Code.GenericMethod<T>(int)' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "GenericMethod<int>").WithArguments("Code.GenericMethod<T>(int)", "T", "int").WithLocation(9, 9)); } [Fact] public void CS0457ERR_AmbigUDConv() { var text = @" public class A { } public class G0 { } public class G1<R> : G0 { } public class H0 { public static implicit operator G0(H0 h) { return new G0(); } } public class H1<R> : H0 { public static implicit operator G1<R>(H1<R> h) { return new G1<R>(); } } public class Test { public static void F0(G0 g) { } public static void Main() { H1<A> h1a = new H1<A>(); F0(h1a); // CS0457 } } "; CreateCompilation(text).VerifyDiagnostics( // (24,10): error CS0457: Ambiguous user defined conversions 'H1<A>.implicit operator G1<A>(H1<A>)' and 'H0.implicit operator G0(H0)' when converting from 'H1<A>' to 'G0' Diagnostic(ErrorCode.ERR_AmbigUDConv, "h1a").WithArguments("H1<A>.implicit operator G1<A>(H1<A>)", "H0.implicit operator G0(H0)", "H1<A>", "G0")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void AddrOnReadOnlyLocal() { var text = @" class A { public unsafe void M1() { int[] ints = new int[] { 1, 2, 3 }; foreach (int i in ints) { int *j = &i; } fixed (int *i = &_i) { int **j = &i; } } private int _i = 0; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CS0463ERR_DecConstError() { var text = @" using System; class MyClass { public static void Main() { const decimal myDec = 79000000000000000000000000000.0m + 79000000000000000000000000000.0m; // CS0463 Console.WriteLine(myDec.ToString()); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DecConstError, Line = 7, Column = 31 } }); } [WorkItem(543272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543272")] [Fact] public void CS0463ERR_DecConstError_02() { var text = @" class MyClass { public static void Main() { decimal x1 = decimal.MaxValue + 1; // CS0463 decimal x2 = decimal.MaxValue + decimal.One; // CS0463 decimal x3 = decimal.MinValue - decimal.One; // CS0463 decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x1 = decimal.MaxValue + 1; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + 1"), // (7,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x2 = decimal.MaxValue + decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue + decimal.One"), // (8,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x3 = decimal.MinValue - decimal.One; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue - decimal.One"), // (9,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x4 = decimal.MinValue + decimal.MinusOne; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MinValue + decimal.MinusOne"), // (10,22): error CS0463: Evaluation of the decimal constant expression failed // decimal x5 = decimal.MaxValue - decimal.MinValue; // CS0463 Diagnostic(ErrorCode.ERR_DecConstError, "decimal.MaxValue - decimal.MinValue")); } [Fact()] public void CS0471ERR_TypeArgsNotAllowedAmbig() { var text = @" class Test { public void F(bool x, bool y) {} public void F1() { int a = 1, b = 2, c = 3; F(a<b, c>(3)); // CS0471 // To resolve, try the following instead: // F((a<b), c>(3)); } } "; //Dev11 used to give 'The {1} '{0}' is not a generic method. If you intended an expression list, use parentheses around the &lt; expression.' //Roslyn will be satisfied with something less helpful. var noWarns = new Dictionary<string, ReportDiagnostic>(); noWarns.Add(MessageProvider.Instance.GetIdForErrorCode(219), ReportDiagnostic.Suppress); CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(noWarns)).VerifyDiagnostics( // (8,13): error CS0118: 'b' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "b").WithArguments("b", "variable", "type"), // (8,16): error CS0118: 'c' is a variable but is used like a type // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_BadSKknown, "c").WithArguments("c", "variable", "type"), // (8,11): error CS0307: The variable 'a' cannot be used with type arguments // F(a<b, c>(3)); // CS0471 Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "a<b, c>").WithArguments("a", "variable")); } [Fact] public void CS0516ERR_RecursiveConstructorCall() { var text = @" namespace x { public class clx { public clx() : this() // CS0516 { } public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0516: Constructor 'x.clx.clx()' cannot call itself Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "this").WithArguments("x.clx.clx()")); } [WorkItem(751825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751825")] [Fact] public void Repro751825() { var text = @" public class A : A<int> { public A() : base() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,18): error CS0308: The non-generic type 'A' cannot be used with type arguments // public class A : A<int> Diagnostic(ErrorCode.ERR_HasNoTypeVars, "A<int>").WithArguments("A", "type"), // (4,18): error CS0516: Constructor 'A.A()' cannot call itself // public A() : base() { } Diagnostic(ErrorCode.ERR_RecursiveConstructorCall, "base").WithArguments("A.A()")); } [WorkItem(366, "https://github.com/dotnet/roslyn/issues/366")] [Fact] public void IndirectConstructorCycle() { var text = @" public class A { public A() : this(1) {} public A(int x) : this(string.Empty) {} public A(string s) : this(1) {} public A(long l) : this(double.MaxValue) {} public A(double d) : this(char.MaxValue) {} public A(char c) : this(long.MaxValue) {} public A(short s) : this() {} } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0768: Constructor 'A.A(string)' cannot call itself through another constructor // public A(string s) : this(1) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(1)").WithArguments("A.A(string)").WithLocation(6, 24), // (9,22): error CS0768: Constructor 'A.A(char)' cannot call itself through another constructor // public A(char c) : this(long.MaxValue) {} Diagnostic(ErrorCode.ERR_IndirectRecursiveConstructorCall, ": this(long.MaxValue)").WithArguments("A.A(char)").WithLocation(9, 22) ); } [Fact] public void CS0517ERR_ObjectCallingBaseConstructor() { var text = @"namespace System { public class Void { } //just need the type to be defined public class Object { public Object() : base() { } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (7,16): error CS0517: 'object' has no base class and cannot call a base constructor Diagnostic(ErrorCode.ERR_ObjectCallingBaseConstructor, "Object").WithArguments("object")); } [Fact] public void CS0522ERR_StructWithBaseConstructorCall() { var text = @" public class clx { public clx(int i) { } public static void Main() { } } public struct cly { public cly(int i):base(0) // CS0522 // try the following line instead // public cly(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,11): error CS0522: 'cly': structs cannot call base class constructors Diagnostic(ErrorCode.ERR_StructWithBaseConstructorCall, "cly").WithArguments("cly")); } [Fact] public void CS0543ERR_EnumeratorOverflow01() { var source = @"enum E { A = int.MaxValue - 1, B, C, // CS0543 D, E = C, F, G = B, H, // CS0543 I } "; CreateCompilation(source).VerifyDiagnostics( // (5,5): error CS0543: 'E.C': the enumerator value is too large to fit in its type // C, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "C").WithArguments("E.C").WithLocation(5, 5), // (10,5): error CS0543: 'E.H': the enumerator value is too large to fit in its type // H, // CS0543 Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "H").WithArguments("E.H").WithLocation(10, 5)); } [Fact] public void CS0543ERR_EnumeratorOverflow02() { var source = @"namespace N { enum E : byte { A = 255, B, C } enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } enum G : int { X = int.MinValue, Y = X - 1, Z } } "; CreateCompilation(source).VerifyDiagnostics( // (3,30): error CS0543: 'E.B': the enumerator value is too large to fit in its type // enum E : byte { A = 255, B, C } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "B").WithArguments("N.E.B").WithLocation(3, 30), // (5,42): error CS0220: The operation overflows at compile time in checked mode // enum G : int { X = int.MinValue, Y = X - 1, Z } Diagnostic(ErrorCode.ERR_CheckedOverflow, "X - 1").WithLocation(5, 42), // (4,57): error CS0543: 'F.D': the enumerator value is too large to fit in its type // enum F : short { A = 0x00ff, B = 0x7f00, C = A | B, D } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "D").WithArguments("N.F.D").WithLocation(4, 57)); } [Fact] public void CS0543ERR_EnumeratorOverflow03() { var source = @"enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } "; CreateCompilation(source).VerifyDiagnostics( // (3,84): error CS0543: 'S32.J': the enumerator value is too large to fit in its type // enum S32 : int { A = int.MinValue, B, C, D = -1, E, F, G = int.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S32.J").WithLocation(3, 84), // (4,87): error CS0543: 'S64.J': the enumerator value is too large to fit in its type // enum S64 : long { A = long.MinValue, B, C, D = -1, E, F, G = long.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S64.J").WithLocation(4, 87), // (7,61): error CS0543: 'U32.G': the enumerator value is too large to fit in its type // enum U32 : uint { A = 0, B, C, D = uint.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U32.G").WithLocation(7, 61), // (6,65): error CS0543: 'U16.G': the enumerator value is too large to fit in its type // enum U16 : ushort { A = 0, B, C, D = ushort.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U16.G").WithLocation(6, 65), // (5,60): error CS0543: 'U8.G': the enumerator value is too large to fit in its type // enum U8 : byte { A = 0, B, C, D = byte.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U8.G").WithLocation(5, 60), // (2,90): error CS0543: 'S16.J': the enumerator value is too large to fit in its type // enum S16 : short { A = short.MinValue, B, C, D = -1, E, F, G = short.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S16.J").WithLocation(2, 90), // (1,89): error CS0543: 'S8.J': the enumerator value is too large to fit in its type // enum S8 : sbyte { A = sbyte.MinValue, B, C, D = -1, E, F, G = sbyte.MaxValue - 2, H, I, J, K } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "J").WithArguments("S8.J").WithLocation(1, 89), // (8,63): error CS0543: 'U64.G': the enumerator value is too large to fit in its type // enum U64 : ulong { A = 0, B, C, D = ulong.MaxValue - 2, E, F, G, H } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "G").WithArguments("U64.G").WithLocation(8, 63)); } [Fact] public void CS0543ERR_EnumeratorOverflow04() { string source = string.Format( @"enum A {0} enum B : byte {1} enum C : byte {2} enum D : sbyte {3}", CreateEnumValues(300, "E"), CreateEnumValues(256, "E"), CreateEnumValues(300, "E"), CreateEnumValues(300, "E", sbyte.MinValue)); CreateCompilation(source).VerifyDiagnostics( // (3,1443): error CS0543: 'C.E256': the enumerator value is too large to fit in its type // enum C : byte { E0, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("C.E256").WithLocation(3, 1443), // (4,1451): error CS0543: 'D.E256': the enumerator value is too large to fit in its type // enum D : sbyte { E0 = -128, E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16, E17, E18, E19, E20, E21, E22, E23, E24, E25, E26, E27, E28, E29, E30, E31, E32, E33, E34, E35, E36, E37, E38, E39, E40, E41, E42, E43, E44, E45, E46, E47, E48, E49, E50, E51, E52, E53, E54, E55, E56, E57, E58, E59, E60, E61, E62, E63, E64, E65, E66, E67, E68, E69, E70, E71, E72, E73, E74, E75, E76, E77, E78, E79, E80, E81, E82, E83, E84, E85, E86, E87, E88, E89, E90, E91, E92, E93, E94, E95, E96, E97, E98, E99, E100, E101, E102, E103, E104, E105, E106, E107, E108, E109, E110, E111, E112, E113, E114, E115, E116, E117, E118, E119, E120, E121, E122, E123, E124, E125, E126, E127, E128, E129, E130, E131, E132, E133, E134, E135, E136, E137, E138, E139, E140, E141, E142, E143, E144, E145, E146, E147, E148, E149, E150, E151, E152, E153, E154, E155, E156, E157, E158, E159, E160, E161, E162, E163, E164, E165, E166, E167, E168, E169, E170, E171, E172, E173, E174, E175, E176, E177, E178, E179, E180, E181, E182, E183, E184, E185, E186, E187, E188, E189, E190, E191, E192, E193, E194, E195, E196, E197, E198, E199, E200, E201, E202, E203, E204, E205, E206, E207, E208, E209, E210, E211, E212, E213, E214, E215, E216, E217, E218, E219, E220, E221, E222, E223, E224, E225, E226, E227, E228, E229, E230, E231, E232, E233, E234, E235, E236, E237, E238, E239, E240, E241, E242, E243, E244, E245, E246, E247, E248, E249, E250, E251, E252, E253, E254, E255, E256, E257, E258, E259, E260, E261, E262, E263, E264, E265, E266, E267, E268, E269, E270, E271, E272, E273, E274, E275, E276, E277, E278, E279, E280, E281, E282, E283, E284, E285, E286, E287, E288, E289, E290, E291, E292, E293, E294, E295, E296, E297, E298, E299, } Diagnostic(ErrorCode.ERR_EnumeratorOverflow, "E256").WithArguments("D.E256").WithLocation(4, 1451)); } // Create string "{ E0, E1, ..., En }" private static string CreateEnumValues(int count, string prefix, int? initialValue = null) { var builder = new System.Text.StringBuilder("{ "); for (int i = 0; i < count; i++) { builder.Append(prefix); builder.Append(i); if ((i == 0) && (initialValue != null)) { builder.AppendFormat(" = {0}", initialValue.Value); } builder.Append(", "); } builder.Append(" }"); return builder.ToString(); } // CS0570 --> Symbols\OverriddenOrHiddenMembersTests.cs [Fact] public void CS0571ERR_CantCallSpecialMethod01() { var source = @"class C { protected virtual object P { get; set; } static object Q { get; set; } void M(D d) { this.set_P(get_Q()); D.set_Q(d.get_P()); ((this.get_P))(); } } class D : C { protected override object P { get { return null; } set { } } } "; CreateCompilation(source).VerifyDiagnostics( // (7,20): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("C.Q.get").WithLocation(7, 20), // (7,14): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // this.set_P(get_Q()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("C.P.set").WithLocation(7, 14), // (8,19): error CS0571: 'D.P.get': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("D.P.get").WithLocation(8, 19), // (8,11): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // D.set_Q(d.get_P()); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("C.Q.set").WithLocation(8, 11), // (9,16): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // ((this.get_P))(); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("C.P.get").WithLocation(9, 16)); // CONSIDER: Dev10 reports 'C.P.get' for the fourth error. Roslyn reports 'D.P.get' // because it is in the more-derived type and because Binder.LookupMembersInClass // calls MergeHidingLookups(D.P.get, C.P.get) with both arguments non-viable // (i.e. keeps current, since new value isn't better). } [Fact] public void CS0571ERR_CantCallSpecialMethod02() { var source = @"using System; namespace A.B { class C { object P { get; set; } static object Q { get { return 0; } set { } } void M(C c) { Func<object> f = get_P; f = C.get_Q; Action<object> a = c.set_P; a = set_Q; } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,30): error CS0571: 'C.P.get': cannot explicitly call operator or accessor // Func<object> f = get_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_P").WithArguments("A.B.C.P.get").WithLocation(10, 30), // (11,19): error CS0571: 'C.Q.get': cannot explicitly call operator or accessor // f = C.get_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "get_Q").WithArguments("A.B.C.Q.get").WithLocation(11, 19), // (12,34): error CS0571: 'C.P.set': cannot explicitly call operator or accessor // Action<object> a = c.set_P; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_P").WithArguments("A.B.C.P.set").WithLocation(12, 34), // (13,17): error CS0571: 'C.Q.set': cannot explicitly call operator or accessor // a = set_Q; Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "set_Q").WithArguments("A.B.C.Q.set").WithLocation(13, 17)); } /// <summary> /// No errors should be reported if method with /// accessor name is defined in different class. /// </summary> [Fact] public void CS0571ERR_CantCallSpecialMethod03() { var source = @"class A { public object get_P() { return null; } } class B : A { public object P { get; set; } void M() { object o = this.P; o = this.get_P(); } } class C { void M(B b) { object o = b.P; o = b.get_P(); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact()] public void CS0571ERR_CantCallSpecialMethod04() { var compilation = CreateCompilation( @"public class MyClass { public static MyClass operator ++(MyClass c) { return null; } public static void M() { op_Increment(null); // CS0571 } } ").VerifyDiagnostics( // (9,9): error CS0571: 'MyClass.operator ++(MyClass)': cannot explicitly call operator or accessor // op_Increment(null); // CS0571 Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Increment").WithArguments("MyClass.operator ++(MyClass)")); } [Fact] public void CS0571ERR_CantCallSpecialMethod05() { var source = @" using System; public class C { public static void M() { IntPtr.op_Addition(default(IntPtr), 0); IntPtr.op_Subtraction(default(IntPtr), 0); IntPtr.op_Equality(default(IntPtr), default(IntPtr)); IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); IntPtr.op_Explicit(0); } } "; CreateCompilation(source).VerifyDiagnostics( // (7,16): error CS0571: 'IntPtr.operator +(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Addition(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Addition").WithArguments("System.IntPtr.operator +(System.IntPtr, int)").WithLocation(7, 16), // (8,16): error CS0571: 'IntPtr.operator -(IntPtr, int)': cannot explicitly call operator or accessor // IntPtr.op_Subtraction(default(IntPtr), 0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Subtraction").WithArguments("System.IntPtr.operator -(System.IntPtr, int)").WithLocation(8, 16), // (9,16): error CS0571: 'IntPtr.operator ==(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Equality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Equality").WithArguments("System.IntPtr.operator ==(System.IntPtr, System.IntPtr)").WithLocation(9, 16), // (10,16): error CS0571: 'IntPtr.operator !=(IntPtr, IntPtr)': cannot explicitly call operator or accessor // IntPtr.op_Inequality(default(IntPtr), default(IntPtr)); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Inequality").WithArguments("System.IntPtr.operator !=(System.IntPtr, System.IntPtr)").WithLocation(10, 16), // (11,16): error CS0571: 'IntPtr.explicit operator IntPtr(int)': cannot explicitly call operator or accessor // IntPtr.op_Explicit(0); Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Explicit").WithArguments("System.IntPtr.explicit operator System.IntPtr(int)").WithLocation(11, 16)); } [Fact] public void CS0572ERR_BadTypeReference() { var text = @" using System; class C { public class Inner { public static int v = 9; } } class D : C { public static void Main() { C cValue = new C(); Console.WriteLine(cValue.Inner.v); // CS0572 // try the following line instead // Console.WriteLine(C.Inner.v); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadTypeReference, Line = 16, Column = 32 } }); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public class iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny() { var text = @" public class Test { public System.TypedReference[] x; public System.RuntimeArgumentHandle[][] y; } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (4,12): error CS0611: Array elements cannot be of type 'System.TypedReference' // public System.TypedReference[] x; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(4, 12), // (5,12): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // public System.RuntimeArgumentHandle[][] y; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(5, 12)); } [WorkItem(541951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541951")] [Fact] public void CS0611ERR_ArrayElementCantBeRefAny_1() { var text = @"using System; class C { static void M() { var x = new[] { new ArgIterator() }; var y = new[] { new TypedReference() }; var z = new[] { new RuntimeArgumentHandle() }; } }"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45); comp.VerifyDiagnostics( // (6,17): error CS0611: Array elements cannot be of type 'System.ArgIterator' // var x = new[] { new ArgIterator() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new ArgIterator() }").WithArguments("System.ArgIterator").WithLocation(6, 17), // (7,17): error CS0611: Array elements cannot be of type 'System.TypedReference' // var y = new[] { new TypedReference() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new TypedReference() }").WithArguments("System.TypedReference").WithLocation(7, 17), // (8,17): error CS0611: Array elements cannot be of type 'System.RuntimeArgumentHandle' // var z = new[] { new RuntimeArgumentHandle() }; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "new[] { new RuntimeArgumentHandle() }").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 17)); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0619ERR_DeprecatedSymbolStr() { var text = @" using System; namespace a { [Obsolete] class C1 { } [Obsolete(""Obsolescence message"", true)] interface I1 { } public class CI1 : I1 { } public class MainClass { public static void Main() { } } } "; CreateCompilation(text).VerifyDiagnostics( // (11,24): error CS0619: 'a.I1' is obsolete: 'Obsolescence message' // public class CI1 : I1 { } Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "I1").WithArguments("a.I1", "Obsolescence message") ); } [Fact] public void CS0622ERR_ArrayInitToNonArrayType() { var text = @" public class Test { public static void Main () { Test t = { new Test() }; // CS0622 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitToNonArrayType, Line = 6, Column = 18 } }); } [Fact] public void CS0623ERR_ArrayInitInBadPlace() { var text = @" class X { public void goo(int a) { int[] x = { { 4 } }; //CS0623 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitInBadPlace, Line = 6, Column = 21 } }); } [Fact] public void CS0631ERR_IllegalRefParam() { var compilation = CreateCompilation( @"interface I { object this[ref object index] { get; set; } } class C { internal object this[object x, out object y] { get { y = null; return null; } } } struct S { internal object this[out int x, out int y] { set { x = 0; y = 0; } } }"); compilation.VerifyDiagnostics( // (3,17): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 17), // (7,36): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(7, 36), // (11,26): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 26), // (11,37): error CS0631: ref and out are not valid in this context Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(11, 37)); } [WorkItem(529305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529305")] [Fact()] public void CS0664ERR_LiteralDoubleCast() { var text = @" class Example { static void Main() { // CS0664, because 1.0 is interpreted as a double: decimal d1 = 1.0; float f1 = 2.0; } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,22): error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type // decimal d1 = 1.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "1.0").WithArguments("M", "decimal").WithLocation(7, 22), // (8,20): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type // float f1 = 2.0; Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "2.0").WithArguments("F", "float").WithLocation(8, 20), // (7,17): warning CS0219: The variable 'd1' is assigned but its value is never used // decimal d1 = 1.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d1").WithArguments("d1").WithLocation(7, 17), // (8,15): warning CS0219: The variable 'f1' is assigned but its value is never used // float f1 = 2.0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "f1").WithArguments("f1").WithLocation(8, 15)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType() { CreateCompilation(@" class C { void x = default(void); }").VerifyDiagnostics( // (4,22): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (4,5): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void")); } [Fact] public void CS0670ERR_FieldCantHaveVoidType_Var() { CreateCompilationWithMscorlib45(@" var x = default(void); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,17): error CS1547: Keyword 'void' cannot be used in this context Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (2,1): error CS0670: Field cannot have void type Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var")); } [WorkItem(538016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538016")] [Fact] public void CS0687ERR_AliasQualAsExpression() { var text = @" using M = Test; using System; public class Test { public static int x = 77; public static void Main() { Console.WriteLine(M::x); // CS0687 } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ColColWithTypeAlias, "M").WithArguments("M") ); } [Fact] public void CS0704ERR_LookupInTypeVariable() { var text = @"using System; class A { internal class B : Attribute { } internal class C<T> { } } class D<T> where T : A { class E : T.B { } interface I<U> where U : T.B { } [T.B] static object M<U>() { T.C<object> b1 = new T.C<object>(); T<U>.B b2 = null; b1 = default(T.B); object o = typeof(T.C<A>); o = o as T.B; return b1; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,15): error CS0704: Cannot do member lookup in 'T' because it is a type parameter class E : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (10,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // interface I<U> where U : T.B { } Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (11,6): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // [T.B] Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (14,9): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (14,30): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // T.C<object> b1 = new T.C<object>(); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<object>").WithArguments("T"), // (15,9): error CS0307: The type parameter 'T' cannot be used with type arguments // T<U>.B b2 = null; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter"), // (16,22): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // b1 = default(T.B); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T"), // (17,27): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // object o = typeof(T.C<A>); Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.C<A>").WithArguments("T"), // (18,18): error CS0704: Cannot do member lookup in 'T' because it is a type parameter // o = o as T.B; Diagnostic(ErrorCode.ERR_LookupInTypeVariable, "T.B").WithArguments("T") ); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" public static class SC { } public class CMain { public static void Main() { SC sc = new SC(); // CS0712 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_InstantiatingStaticClass, Line = 10, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VarDeclIsStaticClass, Line = 10, Column = 9 }}); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" public static class SC { static void F() { } } public class Test { public static void Main() { object o = new object(); System.Console.WriteLine((SC)o); // CS0716 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ConvertToStaticClass, Line = 12, Column = 34 } }); } [Fact] [WorkItem(36203, "https://github.com/dotnet/roslyn/issues/36203")] public void CS0718_StaticClassError_HasHigherPriorityThanMethodOverloadError() { var code = @" static class StaticClass { } class Code { void GenericMethod<T>(int i) => throw null; void GenericMethod<T>(string s) => throw null; void IncorrectMethodCall() { GenericMethod<StaticClass>(1); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,9): error CS0718: 'StaticClass': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "GenericMethod<StaticClass>").WithArguments("StaticClass").WithLocation(11, 9)); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Locals() { CreateCompilation( @"static class SC { static void M() { SC sc = null; // CS0723 N(sc); var sc2 = new SC(); } static void N(object o) { } }").VerifyDiagnostics( // (5,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "SC").WithArguments("SC"), // (7,19): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC"), // (7,9): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "var").WithArguments("SC")); } [Fact] public void CS0723ERR_VarDeclIsStaticClass_Fields() { CreateCompilationWithMscorlib45(@" static class SC {} var sc2 = new SC(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (4,5): error CS0723: Cannot declare a variable of static type 'SC' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "sc2").WithArguments("SC"), // (4,11): error CS0712: Cannot create an instance of the static class 'SC' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new SC()").WithArguments("SC")); } [Fact] public void CS0724ERR_BadEmptyThrowInFinally() { var text = @" using System; class X { static void Test() { try { throw new Exception(); } catch { try { } finally { throw; // CS0724 } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw").WithLocation(19, 17)); } [Fact, WorkItem(1040213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040213")] public void CS0724ERR_BadEmptyThrowInFinally_Nesting() { var text = @" using System; class X { static void Test(bool b) { try { throw new Exception(); } catch { try { } finally { if (b) throw; // CS0724 try { throw; // CS0724 } catch { throw; // OK } finally { throw; // CS0724 } } } } static void Main() { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw"), // (19,17): error CS0724: A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause Diagnostic(ErrorCode.ERR_BadEmptyThrowInFinally, "throw")); } [Fact] public void CS0747ERR_InvalidInitializerElementInitializer() { var text = @" using System.Collections.Generic; public class C { public static int Main() { var t = new List<int> { Capacity = 2, 1 }; // CS0747 return 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "1")); } [Fact] public void CS0762ERR_PartialMethodToDelegate() { var text = @" public delegate void TestDel(); public partial class C { partial void Part(); public static int Main() { C c = new C(); TestDel td = new TestDel(c.Part); // CS0762 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodToDelegate, Line = 11, Column = 38 } }); } [Fact] public void CS0765ERR_PartialMethodInExpressionTree() { var text = @" using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; public delegate void dele(); public class ConClass { [Conditional(""CONDITION"")] public static void TestMethod() { } } public partial class PartClass : IEnumerable { List<object> list = new List<object>(); partial void Add(int x); public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } static void Main() { Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (30,71): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "1"), // (30,74): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<Func<PartClass>> testExpr1 = () => new PartClass { 1, 2 }; // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "2"), // (31,44): error CS0765: Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees // Expression<dele> testExpr2 = () => ConClass.TestMethod(); // CS0765 Diagnostic(ErrorCode.ERR_PartialMethodInExpressionTree, "ConClass.TestMethod()")); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Local() { CreateCompilation(@" class Test { public static void Main() { var m = Main; var d = s => -1; // CS8917 var e = (string s) => 0; var p = null;//CS0815 var del = delegate(string a) { return -1; }; var v = M(); // CS0815 } static void M() {} }").VerifyDiagnostics( // (7,17): error CS8917: The delegate type could not be inferred. // var d = s => -1; // CS8917 Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "s => -1").WithLocation(7, 17), // (9,13): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null;//CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>").WithLocation(9, 13), // (11,13): error CS0815: Cannot assign void to an implicitly-typed variable // var v = M(); // CS0815 Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "v = M()").WithArguments("void").WithLocation(11, 13)); } [Fact] public void CS0815ERR_ImplicitlyTypedVariableAssignedBadValue_Field() { CreateCompilationWithMscorlib45(@" static void M() {} var m = M; var d = s => -1; var e = (string s) => 0; var p = null; var del = delegate(string a) { return -1; }; var v = M(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (5,9): error CS8917: The delegate type could not be inferred. // var d = s => -1; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "s => -1").WithLocation(5, 9), // (7,5): error CS0815: Cannot assign <null> to an implicitly-typed variable // var p = null; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "p = null").WithArguments("<null>").WithLocation(7, 5), // (9,1): error CS0670: Field cannot have void type // var v = M(); Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "var").WithLocation(9, 1)); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer() { var text = @" class A { public static int Main() { var a; // CS0818 return -1; } }"; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, Line = 6, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVar, Line = 6, Column = 13, IsWarning = true }}); } [Fact] public void CS0818ERR_ImplicitlyTypedVariableWithNoInitializer_Fields() { CreateCompilationWithMscorlib45(@" var a; // CS0818 ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0818: Implicitly-typed variables must be initialized Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "a")); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Locals() { var text = @" class A { public static int Main() { var a = 3, b = 2; // CS0819 return -1; } } "; // In the native compiler we skip post-initial-binding error analysis if there was // an error during the initial binding, so we report only that the "var" declaration // is bad. We do not report warnings like "variable b is assigned but never used". // In Roslyn we do flow analysis even if the initial binding pass produced an error, // so we have extra errors here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 13, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_UnreferencedVarAssg, Line = 6, Column = 20, IsWarning = true }}); } [Fact] public void CS0819ERR_ImplicitlyTypedVariableMultipleDeclarator_Fields() { CreateCompilationWithMscorlib45(@" var goo = 4, bar = 4.5; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,1): error CS0819: Implicitly-typed fields cannot have multiple declarators Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var")); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer() { var text = @" class G { public static int Main() { var a = { 1, 2, 3 }; //CS0820 return -1; } }"; // In the native compilers this code produces two errors, both // "you can't assign an array initializer to an implicitly typed local" and // "you can only use an array initializer to assign to an array type". // It seems like the first error ought to prevent the second. In Roslyn // we only produce the first error. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, Line = 6, Column = 13 }}); } [Fact] public void CS0820ERR_ImplicitlyTypedVariableAssignedArrayInitializer_Fields() { CreateCompilationWithMscorlib45(@" var y = { 1, 2, 3 }; ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "y = { 1, 2, 3 }")); } [Fact] public void CS0821ERR_ImplicitlyTypedLocalCannotBeFixed() { var text = @" class A { static int x; public static int Main() { unsafe { fixed (var p = &x) { } } return -1; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,24): error CS0821: Implicitly-typed local variables cannot be fixed // fixed (var p = &x) { } Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x")); } [Fact] public void CS0822ERR_ImplicitlyTypedLocalCannotBeConst() { var text = @" class A { public static void Main() { const var x = 0; // CS0822.cs const var y = (int?)null + x; } }"; // In the dev10 compiler, the second line reports both that "const var" is illegal // and that the initializer must be a valid constant. This seems a bit odd, so // in Roslyn we just report the first error. Let the user sort out whether they // meant it to be a constant or a variable, and then we can tell them if its a // bad constant. var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): error CS0822: Implicitly-typed variables cannot be constant // const var x = 0; // CS0822.cs Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var x = 0").WithLocation(6, 15), // (7,15): error CS0822: Implicitly-typed variables cannot be constant // const var y = (int?)null + x; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var y = (int?)null + x").WithLocation(7, 15), // (7,23): warning CS0458: The result of the expression is always 'null' of type 'int?' // const var y = (int?)null + x; Diagnostic(ErrorCode.WRN_AlwaysNull, "(int?)null + x").WithArguments("int?").WithLocation(7, 23) ); } [Fact] public void CS0822ERR_ImplicitlyTypedVariableCannotBeConst_Fields() { CreateCompilationWithMscorlib45(@" const var x = 0; // CS0822.cs ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,7): error CS0822: Implicitly-typed variables cannot be constant Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields() { CreateCompilationWithMscorlib45(@" void goo(var arg) { } var goo(int arg) { return 2; } ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (1,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (2,1): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact] public void CS0825ERR_ImplicitlyTypedVariableCannotBeUsedAsTheTypeOfAParameter_Fields2() { CreateCompilationWithMscorlib45(@" T goo<T>() { return default(T); } goo<var>(); ", parseOptions: TestOptions.Script).VerifyDiagnostics( // (2,5): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var")); } [Fact()] public void CS0826ERR_ImplicitlyTypedArrayNoBestType() { var text = @" public class C { delegate void D(); public static void M1() {} public static void M2(int x) {} public static int M3() { return 1; } public static int M4(int x) { return x; } public static int Main() { var z = new[] { 1, ""str"" }; // CS0826 char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826 var a = new [] {}; // CS0826 byte b = 3; var arr = new [] {b, c}; // CS0826 var a1 = new [] {null}; // CS0826 var a2 = new [] {null, null, null}; // CS0826 D[] l1 = new [] {x=>x+1}; // CS0826 D[] l2 = new [] {x=>x+1, x=>{return x + 1;}, (int x)=>x+1, (int x)=>{return x + 1;}, (x, y)=>x + y, ()=>{return 1;}}; // CS0826 D[] d1 = new [] {delegate {}}; // CS0826 D[] d2 = new [] {delegate {}, delegate (){}, delegate {return 1;}, delegate {return;}, delegate(int x){}, delegate(int x){return x;}, delegate(int x, int y){return x + y;}}; // CS0826 var m = new [] {M1, M2, M3, M4}; // CS0826 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 12, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 20, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 22, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 25, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 27, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 28, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 30, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 31, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 33, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, Line = 36, Column = 17 }}); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue() { var text = @" public class C { public static int Main() { var c = new { p1 = null }; // CS0828 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_2() { var text = @" public class C { public static void Main() { var c = new { p1 = Main }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_3() { var text = @" public class C { public static void Main() { var c = new { p1 = Main() }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_4() { var text = @" public class C { public static void Main() { var c = new { p1 = ()=>3 }; // CS0828 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 } }); } [Fact] public void CS0828ERR_AnonymousTypePropertyAssignedBadValue_5() { var text = @" public class C { public static void Main() { var c = new { p1 = delegate { return 1; } // CS0828 }; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 8, Column = 13 } }); } [Fact] public void CS0831ERR_ExpressionTreeContainsBaseAccess() { var text = @" using System; using System.Linq.Expressions; public class A { public virtual int BaseMethod() { return 1; } } public class C : A { public override int BaseMethod() { return 2; } public int Test(C c) { Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,41): error CS0831: An expression tree may not contain a base access // Expression<Func<int>> e = () => base.BaseMethod(); // CS0831 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBaseAccess, "base") ); } [Fact] public void CS0832ERR_ExpressionTreeContainsAssignment() { var text = @" using System; using System.Linq.Expressions; public class C { public static int Main() { Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Expression<Func<int, int>> e2 = x => x = 5; // CS0843 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e1 = x => x += 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x += 5"), // (10,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> e2 = x => x = 5; // CS0843 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "x = 5") ); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName() { var text = @" public class C { public static int Main() { var c = new { p1 = 1, p1 = 2 }; // CS0833 return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_2() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 return 1; } static string Prop { get; set; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 } }); } [Fact] public void CS0833ERR_AnonymousTypeDuplicatePropertyName_3() { var text = @" public class C { public static int Main() { var c = new { C.Prop, Prop = 2 }; // CS0833 + CS0828 return 1; } static string Prop() { return null; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, Line = 6, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, Line = 6, Column = 31 }}); } [Fact] public void CS0834ERR_StatementLambdaToExpressionTree() { var text = @" using System; using System.Linq.Expressions; public class C { public static void Main() { Expression<Func<int, int>> e = x => { return x; }; // CS0834 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree // Expression<Func<int, int>> e = x => { return x; }; // CS0834 Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, "x => { return x; }") ); } [Fact] public void CS0835ERR_ExpressionTreeMustHaveDelegate() { var text = @" using System.Linq.Expressions; public class Myclass { public static int Main() { Expression<int> e = x => x + 1; // CS0835 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new[] { LinqAssemblyRef }, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ExpressionTreeMustHaveDelegate, Line = 8, Column = 29 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable() { var text = @" using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class MyClass : Attribute { public MyClass(object obj) { } } [MyClass(new { })] // CS0836 public class ClassGoo { } public class Test { public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 11, Column = 10 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable2() { var text = @" public class Test { const object x = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 4, Column = 22 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable3() { var text = @" public class Test { static object y = new { }; private object x = new { }; public static int Main() { return 0; } } "; // NOTE: Actually we assert that #836 is NOT generated DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable4() { var text = @" public class Test { public static int Main(object x = new { }) { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueMustBeConstant, Line = 4, Column = 39 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable5() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0836ERR_AnonymousTypeNotAvailable6() { var text = @" using System; [AttributeUsage(AttributeTargets.All)] public class MyClass : Attribute { public MyClass(object obj) { } } public class Test { [MyClass(new { })] // CS0836 static object y = new { }; public static int Main() { return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonymousTypeNotAvailable, Line = 13, Column = 14 } }); } [Fact] public void CS0837ERR_LambdaInIsAs() { var text = @" namespace TestNamespace { public delegate void Del(); class Test { static int Main() { bool b1 = (() => { }) is Del; // CS0837 bool b2 = delegate() { } is Del;// CS0837 Del d1 = () => { } as Del; // CS0837 Del d2 = delegate() { } as Del; // CS0837 return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(5)).VerifyDiagnostics( // (10,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b1 = (() => { }) is Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => { }) is Del").WithLocation(10, 23), // (11,23): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } is Del").WithLocation(11, 23), // (11,38): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // bool b2 = delegate() { } is Del;// CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(11, 38), // (12,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "() => { } as Del").WithLocation(12, 22), // (12,32): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d1 = () => { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(12, 32), // (13,22): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate() { } as Del").WithLocation(13, 22), // (13,37): warning CS8848: Operator 'as' cannot be used here due to precedence. Use parentheses to disambiguate. // Del d2 = delegate() { } as Del; // CS0837 Diagnostic(ErrorCode.WRN_PrecedenceInversion, "as").WithArguments("as").WithLocation(13, 37) ); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration01() { CreateCompilation( @"class C { static void M() { j = 5; // CS0841 int j; // To fix, move this line up. } } ") // The native compiler just produces the "var used before decl" error; the Roslyn // compiler runs the flow checking pass even if the initial binding failed. We // might consider turning off flow checking if the initial binding failed, and // removing the warning here. .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "j").WithArguments("j"), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "j").WithArguments("j")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration02() { CreateCompilation( @"class C { static void M() { int a = b, b = 0, c = a; for (int x = y, y = 0; ; ) { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration03() { // It is a bit unfortunate that we produce "can't use variable before decl" here // when the variable is being used after the decl. Perhaps we should generate // a better error? CreateCompilation( @"class C { static int N(out int q) { q = 1; return 2;} static void M() { var x = N(out x); } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x")); } [Fact] public void CS0841ERR_VariableUsedBeforeDeclaration04() { var systemRef = Net451.System; CreateCompilationWithMscorlib40AndSystemCore( @"using System.Collections.Generic; class Base { int i; } class Derived : Base { int j; } class C { public static void Main() { HashSet<Base> set1 = new HashSet<Base>(); foreach (Base b in set1) { Derived d = b as Derived; Base b = null; } } } ", new List<MetadataReference> { systemRef }) .VerifyDiagnostics( // (18,25): error CS0841: Cannot use local variable 'b' before it is declared // Derived d = b as Derived; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b"), // (19,18): error CS0136: A local or parameter named 'b' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Base b = null; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "b").WithArguments("b"), // (4,9): warning CS0169: The field 'Base.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("Base.i"), // (8,9): warning CS0169: The field 'Derived.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("Derived.j")); } /// <summary> /// No errors using statics before declaration. /// </summary> [Fact] public void StaticUsedBeforeDeclaration() { var text = @"class C { static int F = G + 2; static int G = F + 1; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0843ERR_UnassignedThisAutoProperty() { var text = @" struct S { public int AIProp { get; set; } public S(int i) { } //CS0843 } class Test { static int Main() { return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_UnassignedThisAutoProperty, Line = 5, Column = 12 } }); } [Fact] public void CS0844ERR_VariableUsedBeforeDeclarationAndHidesField() { var text = @" public class MyClass { int num; public void TestMethod() { num = 5; // CS0844 int num = 6; System.Console.WriteLine(num); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,9): error CS0844: Cannot use local variable 'num' before it is declared. The declaration of the local variable hides the field 'MyClass.num'. // num = 5; // CS0844 Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, "num").WithArguments("num", "MyClass.num"), // (4,9): warning CS0169: The field 'MyClass.num' is never used // int num; Diagnostic(ErrorCode.WRN_UnreferencedField, "num").WithArguments("MyClass.num") ); } [Fact] public void CS0845ERR_ExpressionTreeContainsBadCoalesce() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Expression<Func<object>> e = () => null ?? ""x""; // CS0845 } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,48): error CS0845: An expression tree lambda may not contain a coalescing operator with a null literal left-hand side // Expression<Func<object>> e = () => null ?? "x"; // CS0845 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null") ); } [WorkItem(3717, "DevDiv_Projects/Roslyn")] [Fact] public void CS0846ERR_ArrayInitializerExpected() { var text = @"public class Myclass { public static void Main() { int[,] a = new int[,] { 1 }; // error } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayInitializerExpected, Line = 5, Column = 33 } }); } [Fact] public void CS0847ERR_ArrayInitializerIncorrectLength() { var text = @" public class Program { public static void Main(string[] args) { int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected ar0[0] = ar1[0]; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,31): error CS0847: An array initializer of length '0' is expected // int[] ar0 = new int[0]{0}; // error CS0847: An array initializer of length `0' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{0}").WithArguments("0").WithLocation(6, 31), // (7,31): error CS0847: An array initializer of length '3' is expected // int[] ar1 = new int[3]{}; // error CS0847: An array initializer of length `3' was expected Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{}").WithArguments("3").WithLocation(7, 31)); } [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(minSessions:5); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0853: An expression tree may not contain a named argument specification // Expression<dg> myET = x => Index(minSessions:5); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "Index(minSessions:5)").WithLocation(10, 40) ); } [WorkItem(545063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545063")] [Fact] public void CS0853ERR_ExpressionTreeContainsNamedArgument02() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class A { static void Main() { Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,41): error CS0853: An expression tree may not contain a named argument specification // Expression<Func<int>> f = () => new List<int> { 1 } [index: 0]; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsNamedArgument, "new List<int> { 1 } [index: 0]").WithLocation(10, 41) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument01() { var text = @" using System.Linq.Expressions; namespace ConsoleApplication3 { class Program { delegate string dg(int x); static void Main(string[] args) { Expression<dg> myET = x => Index(); } public static string Index(int minSessions = 0) { return minSessions.ToString(); } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,40): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // Expression<dg> myET = x => Index(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "Index()").WithLocation(10, 40) ); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument02() { var text = @"using System; using System.Linq.Expressions; class A { internal object this[int x, int y = 2] { get { return null; } } } class B { internal object this[int x, int y = 2] { set { } } } class C { static void M(A a, B b) { Expression<Func<object>> e1; e1 = () => a[0]; e1 = () => a[1, 2]; Expression<Action> e2; e2 = () => b[3] = null; e2 = () => b[4, 5] = null; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (22,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "a[0]").WithLocation(22, 20), // (25,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[3] = null").WithLocation(25, 20), // (25,20): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "b[3]").WithLocation(25, 20), // (26,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "b[4, 5] = null").WithLocation(26, 20)); } [Fact] public void CS0854ERR_ExpressionTreeContainsOptionalArgument03() { var text = @"using System; using System.Collections; using System.Linq.Expressions; public class Collection : IEnumerable { public void Add(int i, int j = 0) { } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public class C { public void M() { Expression<Func<Collection>> expr = () => new Collection { 1 }; // 1 } }"; CreateCompilation(text).VerifyDiagnostics( // (18,36): error CS0854: An expression tree may not contain a call or invocation that uses optional arguments // () => new Collection { 1 }; // 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOptionalArgument, "1").WithLocation(18, 36)); } [Fact] public void CS0855ERR_ExpressionTreeContainsIndexedProperty() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface I Property P(index As Object) As Integer Property Q(Optional index As Object = Nothing) As Integer End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"using System; using System.Linq.Expressions; class C { static void M(I i) { Expression<Func<int>> e1; e1 = () => i.P[1]; e1 = () => i.get_P(2); // no error e1 = () => i.Q; e1 = () => i.Q[index:3]; Expression<Action> e2; e2 = () => i.P[4] = 0; e2 = () => i.set_P(5, 6); // no error } }"; var compilation2 = CreateCompilationWithMscorlib40AndSystemCore(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[1]").WithLocation(8, 20), // (10,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q").WithLocation(10, 20), // (11,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.Q[index:3]").WithLocation(11, 20), // (13,20): error CS0832: An expression tree may not contain an assignment operator Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "i.P[4] = 0").WithLocation(13, 20), // (13,20): error CS0855: An expression tree may not contain an indexed property Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIndexedProperty, "i.P[4]").WithLocation(13, 20)); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23004, "https://github.com/dotnet/roslyn/issues/23004")] public void CS0856ERR_IndexedPropertyRequiresParams01() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface I Property P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static void M(I i) { object o; o = i.P; // CS0856 (Dev11) o = i.Q; i.R = o; // CS0856 i.R[1] = o; // CS1501 o = i.S; // CS0856 (Dev11) i.S = o; // CS0856 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,9): error CS0856: Indexed property 'I.R' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "i.R").WithArguments("I.R").WithLocation(8, 9), // (9,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'I.R[int, int, int]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "i.R[1]").WithArguments("y", "I.R[int, int, int]").WithLocation(9, 9)); var tree = compilation2.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i.R[1]", node.ToString()); compilation2.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid) (Syntax: 'i.R[1]') Children(2): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: I, IsInvalid) (Syntax: 'i') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void CS0856ERR_IndexedPropertyRequiresParams02() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Protected ReadOnly Property P(Optional o As Object = Nothing) As Object Get Return Nothing End Get End Property Public ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C { static object F(A a) { return a.P; } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (5,16): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "a.P").WithArguments("A.P").WithLocation(5, 16)); } [Fact] public void CS0857ERR_IndexedPropertyMustHaveAllOptionalParams() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> <CoClass(GetType(A))> Public Interface IA Property P(x As Object, Optional y As Object = Nothing) As Object Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Property Q(x As Object, Optional y As Object = Nothing) As Object Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Property S(ParamArray args As Integer()) As Object End Interface Public Class A Implements IA Property P(x As Object, Optional y As Object = Nothing) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property P(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.P Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(Optional x As Integer = 1, Optional y As Integer = 2) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property Q(x As Object, Optional y As Object = Nothing) As Object Implements IA.Q Get Return Nothing End Get Set(value As Object) End Set End Property Property R(x As Integer, y As Integer, Optional z As Integer = 3) As Object Implements IA.R Get Return Nothing End Get Set(value As Object) End Set End Property Property S(ParamArray args As Integer()) As Object Implements IA.S Get Return Nothing End Get Set(value As Object) End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes); var source2 = @"class B { static void M() { IA a; a = new IA() { P = null }; // CS0857 (Dev11) a = new IA() { Q = null }; a = new IA() { R = null }; // CS0857 a = new IA() { S = null }; // CS0857 (Dev11) } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,24): error CS0857: Indexed property 'IA.R' must have all arguments optional Diagnostic(ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams, "R").WithArguments("IA.R").WithLocation(8, 24)); } [Fact] public void CS1059ERR_IncrementLvalueExpected01() { var text = @"enum E { A, B } class C { static void M() { ++E.A; // CS1059 E.A++; // CS1059 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 6, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_IncrementLvalueExpected, Line = 7, Column = 9 }); } [Fact] public void CS1059ERR_IncrementLvalueExpected02() { var text = @"class C { const int field = 0; static void M() { const int local = 0; ++local; local++; --field; field--; ++(local + 3); (local + 3)++; --2; 2--; dynamic d = null; (d + 1)++; --(d + 1); d++++; } } "; CreateCompilation(text).VerifyDiagnostics( // (7,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (8,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local"), // (9,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (10,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "field"), // (11,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (12,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "local + 3"), // (13,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (14,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "2"), // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (18,12): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d + 1"), // (19,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "d++")); } [Fact] public void CS1059ERR_IncrementLvalueExpected03() { var text = @" class C { void M() { ++this; // CS1059 this--; // CS1059 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // ++this; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this"), // (7,9): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // this--; // CS1059 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "this").WithArguments("this")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension01() { var text = @" public class TestClass1 { public void WriteSomething(string s) { System.Console.WriteLine(s); } } public class TestClass2 { public void DisplaySomething(string s) { System.Console.WriteLine(s); } } public class TestTheClasses { public static void Main() { TestClass1 tc1 = new TestClass1(); TestClass2 tc2 = new TestClass2(); if (tc1 == null | tc2 == null) {} tc1.DisplaySomething(""Hello""); // CS1061 } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NoSuchMemberOrExtension, Line = 25, Column = 13 } }); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension02() { var source = @"enum E { } class C { static void M(E e) { object o = e.value__; } }"; CreateCompilation(source).VerifyDiagnostics( // (6,22): error CS1061: 'E' does not contain a definition for 'value__' and no extension method 'value__' accepting a first argument of type 'E' could be found (are you missing a using directive or an assembly reference?) // object o = e.value__; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "value__").WithArguments("E", "value__").WithLocation(6, 22)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension03() { CreateCompilation( @"class A { } class B { void M() { this.F(); this.P = this.Q; } static void M(A a) { a.F(); a.P = a.Q; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("A", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("A", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("A", "Q"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "F").WithArguments("B", "F"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("B", "P"), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Q").WithArguments("B", "Q")); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension04() { CreateCompilation( @"using System.Collections.Generic; class C { static void M(List<object> list) { object o = list.Item; list.Item = o; } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(6, 25), Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Item").WithArguments("System.Collections.Generic.List<object>", "Item").WithLocation(7, 14)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension05() { CreateCompilationWithMscorlib40AndSystemCore( @"using System.Linq; class Test { static void Main() { var q = 1.Select(z => z); } } ") .VerifyDiagnostics( // (7,17): error CS1061: 'int' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // var q = 1.Select(z => z); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Select").WithArguments("int", "Select").WithLocation(7, 19)); } [Fact] public void CS1061ERR_NoSuchMemberOrExtension06() { var source = @"interface I<T> { } static class C { static void M(object o) { o.M1(o, o); o.M2(o, o); } static void M1<T>(this I<T> o, object arg) { } static void M2<T>(this I<T> o, params object[] args) { } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'M1' takes 2 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "2").WithLocation(6, 11), // (7,9): error CS1061: 'object' does not contain a definition for 'M2' and no extension method 'M2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M2").WithArguments("object", "M2").WithLocation(7, 11)); } [Fact] public void CS1113ERR_ValueTypeExtDelegate01() { var source = @"class C { public void M() { } } interface I { void M(); } enum E { } struct S { public void M() { } } static class SC { static void Test(C c, I i, E e, S s, double d) { System.Action cm = c.M; // OK -- instance method System.Action cm1 = c.M1; // OK -- extension method on ref type System.Action im = i.M; // OK -- instance method System.Action im2 = i.M2; // OK -- extension method on ref type System.Action em3 = e.M3; // BAD -- extension method on value type System.Action sm = s.M; // OK -- instance method System.Action sm4 = s.M4; // BAD -- extension method on value type System.Action dm5 = d.M5; // BAD -- extension method on value type } static void M1(this C c) { } static void M2(this I i) { } static void M3(this E e) { } static void M4(this S s) { } static void M5(this double d) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (24,29): error CS1113: Extension methods 'SC.M3(E)' defined on value type 'E' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "e.M3").WithArguments("SC.M3(E)", "E").WithLocation(24, 29), // (26,29): error CS1113: Extension methods 'SC.M4(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M4").WithArguments("SC.M4(S)", "S").WithLocation(26, 29), // (27,29): error CS1113: Extension methods 'SC.M5(double)' defined on value type 'double' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "d.M5").WithArguments("SC.M5(double)", "double").WithLocation(27, 29)); } [Fact] public void CS1113ERR_ValueTypeExtDelegate02() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { D d; d = i.M1; d = i.M2<int, object>; d = s.M1; d = s.M2<S, object>; d = t1.M1; d = t1.M2<T1, object>; d = t2.M1; d = t2.M2<T2, object>; d = t3.M1; d = t3.M2<T3, object>; d = t4.M1; d = t4.M2<T4, object>; d = t5.M1; d = t5.M2<T5, object>; } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (13,13): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(13, 13), // (14,13): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(14, 13), // (15,13): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(15, 13), // (16,13): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(16, 13), // (17,13): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(17, 13), // (18,13): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(18, 13), // (21,13): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(21, 13), // (22,13): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(22, 13), // (23,13): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(23, 13), // (24,13): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(24, 13)); } [WorkItem(528758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528758")] [Fact(Skip = "528758")] public void CS1113ERR_ValueTypeExtDelegate03() { var source = @"delegate void D(); interface I { } struct S { } class C { static void M<T1, T2, T3, T4, T5>(int i, S s, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) where T2 : class where T3 : struct where T4 : I where T5 : C { F(i.M1); F(i.M2<int, object>); F(s.M1); F(s.M2<S, object>); F(t1.M1); F(t1.M2<T1, object>); F(t2.M1); F(t2.M2<T2, object>); F(t3.M1); F(t3.M2<T3, object>); F(t4.M1); F(t4.M2<T4, object>); F(t5.M1); F(t5.M2<T5, object>); } static void F(D d) { } } static class E { internal static void M1<T>(this T t) { } internal static void M2<T, U>(this T t) { } }"; CreateCompilation(source, references: new[] { Net40.SystemCore }).VerifyDiagnostics( // (12,11): error CS1113: Extension methods 'E.M1<int>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M1").WithArguments("E.M1<int>(int)", "int").WithLocation(12, 11), // (13,11): error CS1113: Extension methods 'E.M2<int, object>(int)' defined on value type 'int' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "i.M2<int, object>").WithArguments("E.M2<int, object>(int)", "int").WithLocation(13, 11), // (14,11): error CS1113: Extension methods 'E.M1<S>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M1").WithArguments("E.M1<S>(S)", "S").WithLocation(14, 11), // (15,11): error CS1113: Extension methods 'E.M2<S, object>(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M2<S, object>").WithArguments("E.M2<S, object>(S)", "S").WithLocation(15, 11), // (16,11): error CS1113: Extension methods 'E.M1<T1>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M1").WithArguments("E.M1<T1>(T1)", "T1").WithLocation(16, 11), // (17,11): error CS1113: Extension methods 'E.M2<T1, object>(T1)' defined on value type 'T1' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t1.M2<T1, object>").WithArguments("E.M2<T1, object>(T1)", "T1").WithLocation(17, 11), // (20,11): error CS1113: Extension methods 'E.M1<T3>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M1").WithArguments("E.M1<T3>(T3)", "T3").WithLocation(20, 11), // (21,11): error CS1113: Extension methods 'E.M2<T3, object>(T3)' defined on value type 'T3' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t3.M2<T3, object>").WithArguments("E.M2<T3, object>(T3)", "T3").WithLocation(21, 11), // (22,11): error CS1113: Extension methods 'E.M1<T4>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M1").WithArguments("E.M1<T4>(T4)", "T4").WithLocation(22, 11), // (23,11): error CS1113: Extension methods 'E.M2<T4, object>(T4)' defined on value type 'T4' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "t4.M2<T4, object>").WithArguments("E.M2<T4, object>(T4)", "T4").WithLocation(23, 11)); } [Fact] public void CS1501ERR_BadArgCount() { var text = @" using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ExampleClass ec = new ExampleClass(); ec.ExampleMethod(10, 20); } } class ExampleClass { public void ExampleMethod() { Console.WriteLine(""Zero parameters""); } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgCount, Line = 11, Column = 16 } }); } [Fact] public void CS1502ERR_BadArgTypes() { var text = @" namespace x { public class a { public a(char i) { } public static void Main() { a aa = new a(2222); // CS1502 & CS1503 if (aa == null) {} } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 12, Column = 24 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 12, Column = 26 }}); } [Fact] public void CS1502ERR_BadArgTypes_ConstructorInitializer() { var text = @" namespace x { public class a { public a() : this(""string"") //CS1502, CS1503 { } public a(char i) { } } } "; CreateCompilation(text).VerifyDiagnostics( //// (6,22): error CS1502: The best overloaded method match for 'x.a.a(char)' has some invalid arguments //Diagnostic(ErrorCode.ERR_BadArgTypes, "this").WithArguments("x.a.a(char)"), //specifically omitted by roslyn // (6,27): error CS1503: Argument 1: cannot convert from 'string' to 'char' Diagnostic(ErrorCode.ERR_BadArgType, "\"string\"").WithArguments("1", "string", "char")); } [Fact] public void CS1503ERR_BadArgType01() { var source = @"namespace X { public class C { public C(int i, char c) { } static void M() { new C(1, 2); // CS1502 & CS1503 } } } "; CreateCompilation(source).VerifyDiagnostics( // (10,22): error CS1503: Argument 2: cannot convert from 'int' to 'char' // new C(1, 2); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "2").WithArguments("2", "int", "char").WithLocation(10, 22)); } [Fact] public void CS1503ERR_BadArgType02() { var source = @"enum E1 { A, B, C } enum E2 { X, Y, Z } class C { static void F(int i) { } static void G(E1 e) { } static void M() { F(E1.A); // CS1502 & CS1503 F((E2)E1.B); // CS1502 & CS1503 F((int)E1.C); G(E2.X); // CS1502 & CS1503 G((E1)E2.Y); G((int)E2.Z); // CS1502 & CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,11): error CS1503: Argument 1: cannot convert from 'E1' to 'int' // F(E1.A); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E1.A").WithArguments("1", "E1", "int").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'E2' to 'int' // F((E2)E1.B); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(E2)E1.B").WithArguments("1", "E2", "int").WithLocation(10, 11), // (12,11): error CS1503: Argument 1: cannot convert from 'E2' to 'E1' // G(E2.X); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "E2.X").WithArguments("1", "E2", "E1").WithLocation(12, 11), // (14,11): error CS1503: Argument 1: cannot convert from 'int' to 'E1' // G((int)E2.Z); // CS1502 & CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "(int)E2.Z").WithArguments("1", "int", "E1").WithLocation(14, 11)); } [WorkItem(538939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538939")] [Fact] public void CS1503ERR_BadArgType03() { var source = @"class C { static void F(out int i) { i = 0; } static void M(long arg) { F(out arg); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // F(out arg); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "arg").WithArguments("1", "out long", "out int").WithLocation(9, 15)); } [Fact] public void CS1503ERR_BadArgType_MixedMethodsAndTypes() { var text = @" class A { public static void Goo(int x) { } } class B : A { public class Goo { } } class C : B { public static void Goo(string x) { } static void Main() { ((Goo))(1); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 8, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 22, IsWarning = true }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 16, Column = 5 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 16, Column = 13 } }); } [Fact] public void CS1510ERR_RefLvalueExpected_01() { var text = @"class C { void M(ref int i) { M(ref 2); // CS1510, can't pass a number as a ref parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_RefLvalueExpected, Line = 5, Column = 15 }); } [Fact] public void CS1510ERR_RefLvalueExpected_02() { var text = @"class C { void M() { var a = new System.Action<int>(ref x => x = 1); var b = new System.Action<int, int>(ref (x,y) => x = 1); var c = new System.Action<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_03() { var text = @"class C { void M() { var a = new System.Action<int>(out x => x = 1); var b = new System.Action<int, int>(out (x,y) => x = 1); var c = new System.Action<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,44): error CS1510: A ref or out argument must be an assignable variable // var a = new System.Action<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(5, 44), // (6,49): error CS1510: A ref or out argument must be an assignable variable // var b = new System.Action<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(6, 49), // (7,44): error CS1510: A ref or out argument must be an assignable variable // var c = new System.Action<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(7, 44)); } [Fact] public void CS1510ERR_RefLvalueExpected_04() { var text = @"class C { void Goo<T>(ref System.Action<T> t) {} void Goo<T1,T2>(ref System.Action<T1,T2> t) {} void M() { Goo<int>(ref x => x = 1); Goo<int, int>(ref (x,y) => x = 1); Goo<int>(ref delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(ref (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(ref delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_05() { var text = @"class C { void Goo<T>(out System.Action<T> t) {t = null;} void Goo<T1,T2>(out System.Action<T1,T2> t) {t = null;} void M() { Goo<int>(out x => x = 1); Goo<int, int>(out (x,y) => x = 1); Goo<int>(out delegate (int x) {x = 1;}); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out x => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x = 1").WithLocation(7, 22), // (8,27): error CS1510: A ref or out argument must be an assignable variable // Goo<int, int>(out (x,y) => x = 1); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "(x,y) => x = 1").WithLocation(8, 27), // (9,22): error CS1510: A ref or out argument must be an assignable variable // Goo<int>(out delegate (int x) {x = 1;}); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "delegate (int x) {x = 1;}").WithLocation(9, 22)); } [Fact] public void CS1510ERR_RefLvalueExpected_Strict() { var text = @"class C { void D(int i) {} void M() { System.Action<int> del = D; var a = new System.Action<int>(ref D); var b = new System.Action<int>(out D); var c = new System.Action<int>(ref del); var d = new System.Action<int>(out del); } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (8,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var a = new System.Action<int>(ref D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(8, 44), // (9,44): error CS1657: Cannot pass 'D' as a ref or out argument because it is a 'method group' // var b = new System.Action<int>(out D); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "D").WithArguments("D", "method group").WithLocation(9, 44), // (10,44): error CS0149: Method name expected // var c = new System.Action<int>(ref del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(10, 44), // (11,44): error CS0149: Method name expected // var d = new System.Action<int>(out del); Diagnostic(ErrorCode.ERR_MethodNameExpected, "del").WithLocation(11, 44)); } [Fact] public void CS1511ERR_BaseInStaticMeth() { var text = @" public class A { public int j = 0; } class C : A { public void Method() { base.j = 3; // base allowed here } public static int StaticMethod() { base.j = 3; // CS1511 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInStaticMeth, Line = 16, Column = 7 } }); } [Fact] public void CS1511ERR_BaseInStaticMeth_Combined() { var text = @" using System; class CLS { static CLS() { var x = base.ToString(); } static object FLD = base.ToString(); static object PROP { get { return base.ToString(); } } static object METHOD() { return base.ToString(); } } class A : Attribute { public object P; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS1511: Keyword 'base' is not available in a static method // static object FLD = base.ToString(); Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (6,28): error CS1511: Keyword 'base' is not available in a static method // static CLS() { var x = base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (8,39): error CS1511: Keyword 'base' is not available in a static method // static object PROP { get { return base.ToString(); } } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (9,37): error CS1511: Keyword 'base' is not available in a static method // static object METHOD() { return base.ToString(); } Diagnostic(ErrorCode.ERR_BaseInStaticMeth, "base"), // (14,19): warning CS0649: Field 'A.P' is never assigned to, and will always have its default value null // public object P; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "P").WithArguments("A.P", "null") ); } [Fact] public void CS1512ERR_BaseInBadContext() { var text = @" using System; class Base { } class CMyClass : Base { private String xx = base.ToString(); // CS1512 public static void Main() { CMyClass z = new CMyClass(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 8, Column = 25 } }); } [Fact] public void CS1512ERR_BaseInBadContext_AttributeArgument() { var text = @" using System; [assembly: A(P = base.ToString())] public class A : Attribute { public object P; } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BaseInBadContext, Line = 4, Column = 18 } }); } [Fact] public void CS1520ERR_MemberNeedsType_02() { CreateCompilation( @"class Program { Main() {} Helper() {} \u0050rogram(int x) {} }") .VerifyDiagnostics( // (3,5): error CS1520: Method must have a return type // Main() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Main"), // (4,5): error CS1520: Method must have a return type // Helper() {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Helper").WithLocation(4, 5) ); } [Fact] public void CS1525ERR_InvalidExprTerm() { CreateCompilation( @"public class MyClass { public static int Main() { bool b = string is string; return 1; } }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string")); } [WorkItem(543167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543167")] [Fact] public void CS1525ERR_InvalidExprTerm_1() { CreateCompilation( @"class D { public static void Main() { var s = 1?; } } ") .VerifyDiagnostics( // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,19): error CS1003: Syntax error, ':' expected // var s = 1?; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";"), // (5,19): error CS1525: Invalid expression term ';' // var s = 1?; Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";"), // (5,17): error CS0029: Cannot implicitly convert type 'int' to 'bool' // var s = 1?; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool") ); } [Fact] public void CS1525ERR_InvalidExprTerm_ConditionalOperator() { CreateCompilation( @"class Program { static void Main(string[] args) { int x = 1; int y = 1; System.Console.WriteLine(((x == y)) ?); // Invalid System.Console.WriteLine(((x == y)) ? (x++)); // Invalid System.Console.WriteLine(((x == y)) ? (x++) : (x++) : ((((y++))))); // Invalid System.Console.WriteLine(((x == y)) ? : :); // Invalid } } ") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":"), Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "("), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":"), Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":")); } [WorkItem(528657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528657")] [Fact] public void CS0106ERR_BadMemberFlag() { CreateCompilation( @"new class MyClass { }") .VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadMemberFlag, "MyClass").WithArguments("new")); } [Fact] public void CS1540ERR_BadProtectedAccess01() { var text = @" namespace CS1540 { class Program1 { static void Main() { Employee.PreparePayroll(); } } class Person { protected virtual void CalculatePay() { } } class Manager : Person { protected override void CalculatePay() { } } class Employee : Person { public static void PreparePayroll() { Employee emp1 = new Employee(); Person emp2 = new Manager(); Person emp3 = new Employee(); emp1.CalculatePay(); emp2.CalculatePay(); emp3.CalculatePay(); } } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 34, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadProtectedAccess, Line = 35, Column = 18 }}); } [Fact] public void CS1540ERR_BadProtectedAccess02() { var text = @"class A { protected object F; protected void M() { } protected object P { get; set; } public object Q { get; protected set; } public object R { protected get; set; } public object S { private get; set; } } class B : A { void M(object o) { // base. base.M(); base.P = base.F; base.Q = null; M(base.R); M(base.S); // a. A a = new A(); a.M(); a.P = a.F; a.Q = null; M(a.R); M(a.S); // G(). G().M(); G().P = G().F; G().Q = null; M(G().R); M(G().S); // no qualifier M(); P = F; Q = null; M(R); M(S); // this. this.M(); this.P = this.F; this.Q = null; M(this.R); M(this.S); // ((A)this). ((A)this).M(); ((A)this).P = ((A)this).F; ((A)this).Q = null; M(((A)this).R); M(((A)this).S); } static A G() { return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (21,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(base.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "base.S").WithArguments("A.S"), // (24,11): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (25,11): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (25,17): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.P = a.F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (26,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // a.Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.Q").WithArguments("A.Q", "A", "B"), // (27,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(a.R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "a.R").WithArguments("A.R", "A", "B"), // (28,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(a.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "a.S").WithArguments("A.S"), // (30,13): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (31,13): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (31,21): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().P = G().F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (32,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // G().Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().Q").WithArguments("A.Q", "A", "B"), // (33,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(G().R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "G().R").WithArguments("A.R", "A", "B"), // (34,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(G().S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "G().S").WithArguments("A.S"), // (40,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "S").WithArguments("A.S"), // (46,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(this.S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "this.S").WithArguments("A.S"), // (48,19): error CS1540: Cannot access protected member 'A.M()' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).M(); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "M").WithArguments("A.M()", "A", "B"), // (49,19): error CS1540: Cannot access protected member 'A.P' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "P").WithArguments("A.P", "A", "B"), // (49,33): error CS1540: Cannot access protected member 'A.F' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).P = ((A)this).F; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "F").WithArguments("A.F", "A", "B"), // (50,9): error CS1540: Cannot access protected member 'A.Q' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // ((A)this).Q = null; Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).Q").WithArguments("A.Q", "A", "B"), // (51,11): error CS1540: Cannot access protected member 'A.R' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it) // M(((A)this).R); Diagnostic(ErrorCode.ERR_BadProtectedAccess, "((A)this).R").WithArguments("A.R", "A", "B"), // (52,11): error CS0271: The property or indexer 'A.S' cannot be used in this context because the get accessor is inaccessible // M(((A)this).S); Diagnostic(ErrorCode.ERR_InaccessibleGetter, "((A)this).S").WithArguments("A.S"), // (3,22): warning CS0649: Field 'A.F' is never assigned to, and will always have its default value null // protected object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("A.F", "null") ); } [WorkItem(540271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540271")] [Fact] public void CS0122ERR_BadAccessProtectedCtor() { // It is illegal to access any "protected" instance method with a "this" that is not of the // current class's type. Oddly enough, that includes constructors. It is legal to call // a protected ctor via ": base()" because then the "this" is of the derived type. But // in a derived class you cannot call "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540 whether the offending method is a regular // method or a ctor: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. That's what Roslyn does. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'Base.Base' is inaccessible due to its protection level var text = @"namespace CS0122 { public class Base { protected Base() {} } public class Derived : Base { void M() { Base b = new Base(); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("CS0122.Base.Base()")); } // CS1545ERR_BindToBogusProp2 --> Symbols\Source\EventTests.cs // CS1546ERR_BindToBogusProp1 --> Symbols\Source\PropertyTests.cs [WorkItem(528658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528658")] [Fact()] public void CS1560ERR_FileNameTooLong() { var text = @" #line 1 ""ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"" public class C { public void Main () { } } "; //EDMAURER no need to enforce a limit here. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text);//, //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FileNameTooLong, Line = 1, Column = 25 } }); } [Fact] public void CS1579ERR_ForEachMissingMember() { var text = @" using System; public class MyCollection { int[] items; public MyCollection() { items = new int[5] { 12, 44, 33, 2, 50 }; } MyEnumerator GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public bool MoveNext() { nIndex++; return (nIndex < collection.items.GetLength(0)); } public int Current { get { return (collection.items[nIndex]); } } } public static void Main() { MyCollection col = new MyCollection(); Console.WriteLine(""Values in the collection are:""); foreach (int i in col) // CS1579 { Console.WriteLine(i); } } }"; CreateCompilation(text).VerifyDiagnostics( // (45,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method. // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "col").WithArguments("MyCollection", "collection", "MyCollection.GetEnumerator()"), // (45,27): error CS1579: foreach statement cannot operate on variables of type 'MyCollection' because 'MyCollection' does not contain a public definition for 'GetEnumerator' // foreach (int i in col) // CS1579 Diagnostic(ErrorCode.ERR_ForEachMissingMember, "col").WithArguments("MyCollection", "GetEnumerator")); } [Fact] public void CS1579ERR_ForEachMissingMember02() { var text = @" public class Test { public static void Main(string[] args) { foreach (int x in F(1)) { } } static void F(int x) { } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_ForEachMissingMember, "F(1)").WithArguments("void", "GetEnumerator")); } [Fact] public void CS1593ERR_BadDelArgCount() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(8, 9); // CS1593 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgCount, Line = 21, Column = 9 } }); } [Fact] public void CS1593ERR_BadDelArgCount_02() { var text = @" delegate void MyDelegate1(int x, float y); class Program { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void Main(string[] args) { Program mc = new Program(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1); md1 -= mc.DelegatedMethod; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'y' of 'MyDelegate1' // md1(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "md1").WithArguments("y", "MyDelegate1").WithLocation(11, 9)); } [Fact] public void CS1593ERR_BadDelArgCount_03() { var text = @" using System; class Program { static void Main() { new Action<int>(Console.WriteLine)(1, 1); } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_BadDelArgCount, "new Action<int>(Console.WriteLine)").WithArguments("System.Action<int>", "2")); } [Fact()] public void CS1594ERR_BadDelArgTypes() { var text = @" using System; delegate string func(int i); // declare delegate class a { public static void Main() { func dt = new func(z); x(dt); } public static string z(int j) { Console.WriteLine(j); return j.ToString(); } public static void x(func hello) { hello(""8""); // CS1594 } } "; //EDMAURER Giving errors for the individual argument problems is better than generic "delegate 'blah' has some invalid arguments" DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgType, Line = 21, Column = 15 } }); //new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadDelArgTypes, Line = 21, Column = 9 } }); } // TODO: change this to CS0051 in Roslyn? [Fact] public void CS1604ERR_AssgReadonlyLocal() { var text = @" class C { void M() { this = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS1604: Cannot assign to 'this' because it is read-only Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1605ERR_RefReadonlyLocal() { var text = @" class C { void Test() { Ref(ref this); //CS1605 Out(out this); //CS1605 } static void Ref(ref C c) { } static void Out(out C c) { c = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this"), // (7,17): error CS1605: Cannot pass 'this' as a ref or out argument because it is read-only Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this")); } [Fact] public void CS1612ERR_ReturnNotLValue01() { var text = @" public struct MyStruct { public int Width; } public class ListView { MyStruct ms; public MyStruct Size { get { return ms; } set { ms = value; } } } public class MyClass { public MyClass() { ListView lvi; lvi = new ListView(); lvi.Size.Width = 5; // CS1612 } public static void Main() { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ReturnNotLValue, Line = 23, Column = 9 } }); } /// <summary> /// Breaking change from Dev10. CS1612 is now reported for all value /// types, not just struct types. Specifically, CS1612 is now reported /// for type parameters constrained to "struct". (See also CS0131.) /// </summary> [WorkItem(528821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528821")] [Fact] public void CS1612ERR_ReturnNotLValue02() { var source = @"interface I { object P { get; set; } } struct S : I { public object P { get; set; } } class C<T, U, V> where T : struct, I where U : class, I where V : I { S F1 { get; set; } T F2 { get; set; } U F3 { get; set; } V F4 { get; set; } void M() { F1.P = null; F2.P = null; F3.P = null; F4.P = null; } }"; CreateCompilation(source).VerifyDiagnostics( // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F1' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F1").WithArguments("C<T, U, V>.F1").WithLocation(20, 9), // (20,9): error CS1612: Cannot modify the return value of 'C<T, U, V>.F2' because it is not a variable Diagnostic(ErrorCode.ERR_ReturnNotLValue, "F2").WithArguments("C<T, U, V>.F2").WithLocation(21, 9)); } [Fact] public void CS1615ERR_BadArgExtraRef() { var text = @" class C { public void f(int i) {} public static void Main() { int i = 1; f(ref i); // CS1615 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 7 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgExtraRef, Line = 8, Column = 13 } }); } [Fact()] public void CS1618ERR_DelegateOnConditional() { var text = @" using System.Diagnostics; delegate void del(); class MakeAnError { public static void Main() { del d = new del(ConditionalMethod); // CS1618 } [Conditional(""DEBUG"")] public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,25): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // del d = new del(ConditionalMethod); // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(10, 25)); } [Fact()] public void CS1618ERR_DelegateOnConditional_02() { var text = @" using System; using System.Diagnostics; delegate void del(); class MakeAnError { class Goo: Attribute { public Goo(object o) {} } [Conditional(""DEBUG"")] [Goo(new del(ConditionalMethod))] // CS1618 public static void ConditionalMethod() { } } "; CreateCompilation(text).VerifyDiagnostics( // (15,18): error CS1618: Cannot create delegate with 'MakeAnError.ConditionalMethod()' because it has a Conditional attribute // [Goo(new del(ConditionalMethod))] // CS1618 Diagnostic(ErrorCode.ERR_DelegateOnConditional, "ConditionalMethod").WithArguments("MakeAnError.ConditionalMethod()").WithLocation(15, 18)); } [Fact] public void CS1620ERR_BadArgRef() { var text = @" class C { void f(ref int i) { } public static void Main() { int x = 1; f(out x); // CS1620 - f takes a ref parameter, not an out parameter } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgTypes, Line = 8, Column = 9 }, //specifically omitted by roslyn new ErrorDescription { Code = (int)ErrorCode.ERR_BadArgRef, Line = 8, Column = 15 } }); } [Fact] public void CS1621ERR_YieldInAnonMeth() { var text = @" using System.Collections; delegate object MyDelegate(); class C : IEnumerable { public IEnumerator GetEnumerator() { MyDelegate d = delegate { yield return this; // CS1621 return this; }; d(); } public static void Main() { } } "; var comp = CreateCompilation(text); var expected = new DiagnosticDescription[] { // (12,13): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield return this; // CS1621 Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // (8,24): error CS0161: 'C.GetEnumerator()': not all code paths return a value // public IEnumerator GetEnumerator() Diagnostic(ErrorCode.ERR_ReturnExpected, "GetEnumerator").WithArguments("C.GetEnumerator()") }; comp.VerifyDiagnostics(expected); comp.VerifyEmitDiagnostics(expected); } [Fact] public void CS1622ERR_ReturnInIterator() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { return (IEnumerator) this; // CS1622 yield return this; // OK } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (8,7): error CS1622: Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration. // return (IEnumerator) this; // CS1622 Diagnostic(ErrorCode.ERR_ReturnInIterator, "return"), // (9,7): warning CS0162: Unreachable code detected // yield return this; // OK Diagnostic(ErrorCode.WRN_UnreachableCode, "yield") ); } [Fact] public void CS1623ERR_BadIteratorArgType() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { yield return 0; } public IEnumerator GetEnumerator(ref int i) // CS1623 { yield return i; } public IEnumerator GetEnumerator(out float f) // CS1623 { f = 0.0F; yield return f; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (11,46): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(ref int i) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "i"), // (16,48): error CS1623: Iterators cannot have ref, in or out parameters // public IEnumerator GetEnumerator(out float f) // CS1623 Diagnostic(ErrorCode.ERR_BadIteratorArgType, "f") ); } [Fact] public void CS1624ERR_BadIteratorReturn() { var text = @" class C { public int Iterator { get // CS1624 { yield return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadIteratorReturn, Line = 6, Column = 9 } }); } [Fact] public void CS1625ERR_BadYieldInFinally() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { } finally { yield return this; // CS1625 } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,9): error CS1625: Cannot yield in the body of a finally clause // yield return this; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield") ); } [Fact] public void CS1626ERR_BadYieldInTryOfCatch() { var text = @" using System.Collections; class C : IEnumerable { public IEnumerator GetEnumerator() { try { yield return this; // CS1626 } catch { } } } public class CMain { public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,10): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return this; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield") ); } [Fact] public void CS1628ERR_AnonDelegateCantUse() { var text = @" delegate int MyDelegate(); class C { public static void F(ref int i) { MyDelegate d = delegate { return i; }; // CS1628 } public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonDelegateCantUse, Line = 8, Column = 42 } }); } [Fact] public void CS1629ERR_IllegalInnerUnsafe() { var text = @" using System.Collections.Generic; class C { IEnumerator<int> IteratorMeth() { int i; unsafe // CS1629 { int *p = &i; yield return *p; } } unsafe IEnumerator<int> IteratorMeth2() { // CS1629 yield break; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,7): error CS1629: Unsafe code may not appear in iterators // unsafe // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe"), // (9,10): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int *"), // (9,19): error CS1629: Unsafe code may not appear in iterators // int *p = &i; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&i"), // (10,24): error CS1629: Unsafe code may not appear in iterators // yield return *p; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "p"), // (14,29): error CS1629: Unsafe code may not appear in iterators // unsafe IEnumerator<int> IteratorMeth2() { // CS1629 Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "IteratorMeth2") ); } [Fact] public void CS1631ERR_BadYieldInCatch() { var text = @" using System; using System.Collections; public class C : IEnumerable { public IEnumerator GetEnumerator() { try { } catch(Exception e) { yield return this; // CS1631 } } public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,9): error CS1631: Cannot yield a value in the body of a catch clause // yield return this; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (12,23): warning CS0168: The variable 'e' is declared but never used // catch(Exception e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e") ); } [Fact] public void CS1632ERR_BadDelegateLeave() { var text = @" delegate void MyDelegate(); class MyClass { public void Test() { for (int i = 0 ; i < 5 ; i++) { MyDelegate d = delegate { break; // CS1632 }; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,13): error CS1632: Control cannot leave the body of an anonymous method or lambda expression // break; // CS1632 Diagnostic(ErrorCode.ERR_BadDelegateLeave, "break") ); } [Fact] public void CS1636ERR_VarargsIterator() { var text = @"using System.Collections; public class Test { IEnumerable Goo(__arglist) { yield return 1; } static int Main(string[] args) { return 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,17): error CS1636: __arglist is not allowed in the parameter list of iterators // IEnumerable Goo(__arglist) Diagnostic(ErrorCode.ERR_VarargsIterator, "Goo")); } [Fact] public void CS1637ERR_UnsafeIteratorArgType() { var text = @" using System.Collections; public unsafe class C { public IEnumerator Iterator1(int* p) // CS1637 { yield return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,39): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p")); } [Fact()] public void CS1639ERR_BadCoClassSig() { // BREAKING CHANGE: Dev10 allows this test to compile, even though the output assembly is not verifiable and generates a runtime exception: // BREAKING CHANGE: We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""00020810-0000-0000-C000-000000000046"")] [CoClass(typeof(GenericClass<>))] public interface InterfaceType {} public class GenericClass<T>: InterfaceType {} public class Program { public static void Main() { var i = new InterfaceType(); } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_BadCoClassSig, Line = 12, Column = 41 } } ); } [Fact()] public void CS1640ERR_MultipleIEnumOfT() { var text = @" using System.Collections; using System.Collections.Generic; public class C : IEnumerable, IEnumerable<int>, IEnumerable<string> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { yield break; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { yield break; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)((IEnumerable<string>)this).GetEnumerator(); } } public class Test { public static int Main() { foreach (int i in new C()) { } // CS1640 return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_MultipleIEnumOfT, Line = 27, Column = 27 } }); } [WorkItem(7389, "DevDiv_Projects/Roslyn")] [Fact] public void CS1640ERR_MultipleIEnumOfT02() { var text = @" using System.Collections.Generic; public class Test { public static void Main(string[] args) { } } public class C<T> where T : IEnumerable<int>, IEnumerable<string> { public static void TestForeach(T t) { foreach (int i in t) { } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t").WithArguments("T", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t").WithArguments("T", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS1643ERR_AnonymousReturnExpected() { var text = @" delegate int MyDelegate(); class C { static void Main() { MyDelegate d = delegate { // CS1643 int i = 0; if (i == 0) return 1; }; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS1643: Not all code paths return a value in anonymous method of type 'MyDelegate' // MyDelegate d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "MyDelegate").WithLocation(8, 24) ); } [Fact] public void CS1643ERR_AnonymousReturnExpected_Foreach() { var text = @" using System; public class Test { public static void Main(string[] args) { string[] arr = null; Func<int> f = () => { foreach (var x in arr) return x; }; } } "; CreateCompilation(text). VerifyDiagnostics( // (8,61): error CS0029: Cannot implicitly convert type 'string' to 'int' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("string", "int").WithLocation(8, 61), // (8,61): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x").WithArguments("lambda expression").WithLocation(8, 61), // (8,26): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>' // Func<int> f = () => { foreach (var x in arr) return x; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(8, 26) ); } [Fact] public void CS1648ERR_AssgReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void Main() { Outer outer = new Outer(); outer.inner.i = 1; // CS1648 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AssgReadonly2, Line = 17, Column = 7 } }); } [Fact] public void CS1649ERR_RefReadonly2() { var text = @" public struct Inner { public int i; } class Outer { public readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { Outer outer = new Outer(); f(ref outer.inner.i); // CS1649 } } "; CreateCompilation(text).VerifyDiagnostics( // (21,15): error CS1649: Members of readonly field 'Outer.inner' cannot be used as a ref or out value (except in a constructor) // f(ref outer.inner.i); // CS1649 Diagnostic(ErrorCode.ERR_RefReadonly2, "outer.inner.i").WithArguments("Outer.inner").WithLocation(21, 15) ); } [Fact] public void CS1650ERR_AssgReadonlyStatic2() { string text = @"public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void Main() { Outer.inner.i = 1; // CS1650 } } "; CreateCompilation(text).VerifyDiagnostics( // (15,9): error CS1650: Fields of static readonly field 'Outer.inner' cannot be assigned to (except in a static constructor or a variable initializer) Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1651ERR_RefReadonlyStatic2() { var text = @" public struct Inner { public int i; } class Outer { public static readonly Inner inner = new Inner(); } class D { static void f(ref int iref) { } static void Main() { f(ref Outer.inner.i); // CS1651 } } "; CreateCompilation(text).VerifyDiagnostics( // (20,15): error CS1651: Fields of static readonly field 'Outer.inner' cannot be passed ref or out (except in a static constructor) Diagnostic(ErrorCode.ERR_RefReadonlyStatic2, "Outer.inner.i").WithArguments("Outer.inner")); } [Fact] public void CS1654ERR_AssgReadonlyLocal2Cause() { var text = @" using System.Collections.Generic; namespace CS1654 { struct Book { public string Title; public string Author; public double Price; public Book(string t, string a, double p) { Title = t; Author = a; Price = p; } } class Program { List<Book> list; static void Main(string[] args) { Program prog = new Program(); prog.list = new List<Book>(); foreach (Book b in prog.list) { b.Price += 9.95; // CS1654 } } } }"; CreateCompilation(text).VerifyDiagnostics( // (29,17): error CS1654: Cannot modify members of 'b' because it is a 'foreach iteration variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocal2Cause, "b.Price").WithArguments("b", "foreach iteration variable")); } [Fact] public void CS1655ERR_RefReadonlyLocal2Cause() { var text = @" struct S { public int i; } class CMain { static void f(ref int iref) { } public static void Main() { S[] sa = new S[10]; foreach(S s in sa) { CMain.f(ref s.i); // CS1655 } } } "; CreateCompilation(text).VerifyDiagnostics( // (18,21): error CS1655: Cannot pass fields of 's' as a ref or out argument because it is a 'foreach iteration variable' // CMain.f(ref s.i); // CS1655 Diagnostic(ErrorCode.ERR_RefReadonlyLocal2Cause, "s.i").WithArguments("s", "foreach iteration variable") ); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause01() { var text = @" using System; class C : IDisposable { public void Dispose() { } } class CMain { unsafe public static void Main() { using (C c = new C()) { c = new C(); // CS1656 } int[] ary = new int[] { 1, 2, 3, 4 }; fixed (int* p = ary) { p = null; // CS1656 } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,13): error CS1656: Cannot assign to 'c' because it is a 'using variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "c").WithArguments("c", "using variable").WithLocation(15, 13), // (19,13): error CS1656: Cannot assign to 'p' because it is a 'fixed variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "p").WithArguments("p", "fixed variable").WithLocation(21, 13)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause02() { var text = @"class C { static void M() { M = null; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,9): error CS1656: Cannot assign to 'M' because it is a 'method group' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "M").WithArguments("M", "method group").WithLocation(5, 9)); } [Fact] public void CS1656ERR_AssgReadonlyLocalCause_NestedForeach() { var text = @" public class Test { static public void Main(string[] args) { string S = ""ABC""; string T = ""XYZ""; foreach (char x in S) { foreach (char y in T) { x = 'M'; } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable")); } [Fact] public void CS1657ERR_RefReadonlyLocalCause() { var text = @" class C { static void F(ref string s) { } static void Main(string[] args) { foreach (var a in args) { F(ref a); //CS1657 } } } "; CreateCompilation(text).VerifyDiagnostics( // (12,19): error CS1657: Cannot use 'a' as a ref or out value because it is a 'foreach iteration variable' // F(ref a); //CS1657 Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "a").WithArguments("a", "foreach iteration variable").WithLocation(12, 19) ); } [Fact] public void CS1660ERR_AnonMethToNonDel() { var text = @" delegate int MyDelegate(); class C { static void Main() { int i = delegate { return 1; }; // CS1660 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_AnonMethToNonDel, Line = 6, Column = 14 } }); } [Fact] public void CS1661ERR_CantConvAnonMethParams() { var text = @" delegate void MyDelegate(int i); class C { public static void Main() { MyDelegate d = delegate(string s) { }; // CS1661 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 8, Column = 40 } }); } [Fact] public void CS1662ERR_CantConvAnonMethReturns() { var text = @" delegate int MyDelegate(int i); class C { delegate double D(); public static void Main() { MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 D dd = () => { return ""Who knows the real sword of Gryffindor?""; }; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,49): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.0").WithArguments("double", "int").WithLocation(9, 49), // (9,49): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // MyDelegate d = delegate(int i) { return 1.0; }; // CS1662 Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1.0").WithArguments("anonymous method").WithLocation(9, 49), // (10,31): error CS0029: Cannot implicitly convert type 'string' to 'double' // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who knows the real sword of Gryffindor?""").WithArguments("string", "double").WithLocation(10, 31), // (10,31): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // D dd = () => { return "Who knows the real sword of Gryffindor?"; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""Who knows the real sword of Gryffindor?""").WithArguments("lambda expression").WithLocation(10, 31) ); } [Fact] public void CS1666ERR_FixedBufferNotFixedErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (13,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(13, 30), // (15,30): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "inst.field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(15, 30), // (22,17): error CS8320: Feature 'indexing movable fixed buffers' is not available in C# 7.2. Please use language version 7.3 or greater. // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "field.buffer").WithArguments("indexing movable fixed buffers", "7.3").WithLocation(22, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotUnsafeErr() { var text = @" unsafe struct S { public fixed int buffer[1]; } class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (13,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // System.Console.Write(inst.field.buffer[0]); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "inst.field.buffer").WithLocation(13, 30), // (20,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // return (field.buffer[0] = 7); // OK Diagnostic(ErrorCode.ERR_UnsafeNeeded, "field.buffer").WithLocation(20, 17) ); } [Fact] public void CS1666ERR_FixedBufferNotFixed() { var text = @" unsafe struct S { public fixed int buffer[1]; } unsafe class Test { public static void Main() { var inst = new Test(); System.Console.Write(inst.example1()); System.Console.Write(inst.field.buffer[0]); System.Console.Write(inst.example2()); System.Console.Write(inst.field.buffer[0]); } S field = new S(); private int example1() { return (field.buffer[0] = 7); // OK } private int example2() { fixed (int* p = field.buffer) { return (p[0] = 8); // OK } } } "; var c = CompileAndVerify(text, expectedOutput: "7788", verify: Verification.Fails, options: TestOptions.UnsafeReleaseExe); c.VerifyIL("Test.example1()", @" { // Code size 22 (0x16) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: ldc.i4.7 IL_0011: dup IL_0012: stloc.0 IL_0013: stind.i4 IL_0014: ldloc.0 IL_0015: ret } "); c.VerifyIL("Test.example2()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (pinned int& V_0, int V_1) IL_0000: ldarg.0 IL_0001: ldflda ""S Test.field"" IL_0006: ldflda ""int* S.buffer"" IL_000b: ldflda ""int S.<buffer>e__FixedBuffer.FixedElementField"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: conv.u IL_0013: ldc.i4.8 IL_0014: dup IL_0015: stloc.1 IL_0016: stind.i4 IL_0017: ldloc.1 IL_0018: ret } "); } [Fact] public void CS1669ERR_IllegalVarArgs01() { var source = @"class C { delegate void D(__arglist); // CS1669 static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS1669: __arglist is not valid in this context // delegate void D(__arglist); // CS1669 Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [Fact] public void CS1669ERR_IllegalVarArgs02() { var source = @"class C { object this[object index, __arglist] { get { return null; } } public static C operator +(C c1, __arglist) { return c1; } public static implicit operator int(__arglist) { return 0; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,31): error CS1669: __arglist is not valid in this context // object this[object index, __arglist] Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (7,38): error CS1669: __arglist is not valid in this context // public static C operator +(C c1, __arglist) { return c1; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist"), // (8,41): error CS1669: __arglist is not valid in this context // public static implicit operator int(__arglist) { return 0; } Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist") ); } [WorkItem(863433, "DevDiv/Personal")] [Fact] public void CS1670ERR_IllegalParams() { // TODO: extra 1670 (not check for now) var test = @" delegate int MyDelegate(params int[] paramsList); class Test { public static int Main() { MyDelegate d = delegate(params int[] paramsList) // CS1670 { return paramsList[0]; }; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(test, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_IllegalParams, Line = 7, Column = 33 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth01() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = this.member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1673ERR_ThisStructNotInAnonMeth02() { var text = @" delegate int MyDelegate(); public struct S { int member; public int F(int i) { member = i; MyDelegate d = delegate() { i = member; // CS1673 return i; }; return d(); } } class CMain { public static void Main() { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_ThisStructNotInAnonMeth, Line = 13, Column = 17 } }); } [Fact] public void CS1674ERR_NoConvToIDisp() { var text = @" class C { public static void Main() { using (int a = 0) // CS1674 using (a); //CS1674 } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): warning CS0642: Possible mistaken empty statement Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (6,16): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int a = 0").WithArguments("int"), // (7,20): error CS1674: 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Diagnostic(ErrorCode.ERR_NoConvToIDisp, "a").WithArguments("int")); } [Fact] public void CS1676ERR_BadParamRef() { var text = @" delegate void E(ref int i); class Errors { static void Main() { E e = delegate(out int i) { }; // CS1676 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,13): error CS1661: Cannot convert anonymous method to delegate type 'E' because the parameter types do not match the delegate parameter types // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "E"), // (7,22): error CS1676: Parameter 1 must be declared with the 'ref' keyword // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_BadParamRef, "i").WithArguments("1", "ref"), // (7,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // E e = delegate(out int i) { }; // CS1676 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1677ERR_BadParamExtraRef() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(out int i) { }; // CS1677 D d = delegate(ref int j) { }; // CS1677 } } "; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (7,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(out int i) { }").WithArguments("anonymous method", "D"), // (7,24): error CS1677: Parameter 1 should not be declared with the 'out' keyword // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "i").WithArguments("1", "out"), // (8,15): error CS1661: Cannot convert anonymous method to delegate type 'D' because the parameter types do not match the delegate parameter types // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "delegate(ref int j) { }").WithArguments("anonymous method", "D"), // (8,24): error CS1677: Parameter 1 should not be declared with the 'ref' keyword // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_BadParamExtraRef, "j").WithArguments("1", "ref"), // (8,11): error CS0128: A local variable named 'd' is already defined in this scope // D d = delegate(ref int j) { }; // CS1677 Diagnostic(ErrorCode.ERR_LocalDuplicate, "d").WithArguments("d"), // (7,15): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // D d = delegate(out int i) { }; // CS1677 Diagnostic(ErrorCode.ERR_ParamUnassigned, "delegate(out int i) { }").WithArguments("i") ); } [Fact] public void CS1678ERR_BadParamType() { var text = @" delegate void D(int i); class Errors { static void Main() { D d = delegate(string s) { }; // CS1678 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_CantConvAnonMethParams, Line = 7, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadParamType, Line = 7, Column = 31 } }); } [Fact] public void CS1681ERR_GlobalExternAlias() { var text = @" extern alias global; class myClass { static int Main() { //global::otherClass oc = new global::otherClass(); return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (2,14): error CS1681: You cannot redefine the global extern alias // extern alias global; Diagnostic(ErrorCode.ERR_GlobalExternAlias, "global"), // (2,14): error CS0430: The extern alias 'global' was not specified in a /reference option // extern alias global; Diagnostic(ErrorCode.ERR_BadExternAlias, "global").WithArguments("global"), // (2,1): info CS8020: Unused extern alias. // extern alias global; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias global;") ); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted() { var text = @" class MyClass { public unsafe delegate int* MyDelegate(); public unsafe int* Test() { int j = 0; MyDelegate d = delegate { return &j; }; // CS1686 return &j; // CS1686 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,42): error CS1686: Local 'j' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // MyDelegate d = delegate { return &j; }; // CS1686 Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&j").WithArguments("j")); } [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted02() { var text = @"using System; unsafe struct S { public fixed int buffer[1]; public int i; } unsafe class Test { private void example1() { S data = new S(); data.i = data.i + 1; Func<S> lambda = () => data; fixed (int* p = data.buffer) // fail due to receiver being a local { } int *q = data.buffer; // fail due to lambda capture } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* p = data.buffer) // fail due to receiver being a local Diagnostic(ErrorCode.ERR_FixedNotNeeded, "data.buffer"), // (19,18): error CS1686: Local 'data' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int *q = data.buffer; // fail due to lambda capture Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "data.buffer").WithArguments("data") ); } [WorkItem(580537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580537")] [Fact] public void CS1686ERR_LocalCantBeFixedAndHoisted03() { var text = @"unsafe public struct Test { private delegate int D(); public fixed int i[1]; public void example() { Test t = this; t.i[0] = 5; D d = delegate { var x = t; return 0; }; } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,9): error CS1686: Local 't' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // t.i[0] = 5; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t") ); } [Fact] public void CS1688ERR_CantConvAnonMethNoParams() { var text = @" using System; delegate void OutParam(out int i); class ErrorCS1676 { static void Main() { OutParam o; o = delegate // CS1688 { Console.WriteLine(""); }; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,31): error CS1010: Newline in constant // Console.WriteLine("); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(11, 31), // (11,34): error CS1026: ) expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(11, 34), // (11,34): error CS1002: ; expected // Console.WriteLine("); Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 34), // (9,13): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'OutParam' because it has one or more out parameters // o = delegate // CS1688 Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, @"delegate // CS1688 { Console.WriteLine(""); }").WithArguments("OutParam").WithLocation(9, 13) ); } [Fact] public void CS1708ERR_FixedNeedsLvalue() { var text = @" unsafe public struct S { public fixed char name[10]; } public unsafe class C { public S UnsafeMethod() { S myS = new S(); return myS; } static void Main() { C myC = new C(); myC.UnsafeMethod().name[3] = 'a'; // CS1708 C._s1.name[3] = 'a'; // CS1648 myC._s2.name[3] = 'a'; // CS1648 } static readonly S _s1; public readonly S _s2; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (18,9): error CS1708: Fixed size buffers can only be accessed through locals or fields // myC.UnsafeMethod().name[3] = 'a'; // CS1708 Diagnostic(ErrorCode.ERR_FixedNeedsLvalue, "myC.UnsafeMethod().name").WithLocation(18, 9), // (19,9): error CS1650: Fields of static readonly field 'C._s1' cannot be assigned to (except in a static constructor or a variable initializer) // C._s1.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonlyStatic2, "C._s1.name[3]").WithArguments("C._s1").WithLocation(19, 9), // (20,9): error CS1648: Members of readonly field 'C._s2' cannot be modified (except in a constructor, an init-only member or a variable initializer) // myC._s2.name[3] = 'a'; // CS1648 Diagnostic(ErrorCode.ERR_AssgReadonly2, "myC._s2.name[3]").WithArguments("C._s2").WithLocation(20, 9) ); } [Fact, WorkItem(543995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543995"), WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")] public void CS1728ERR_DelegateOnNullable() { var text = @" using System; class Test { static void Main() { int? x = null; Func<string> f1 = x.ToString; // no error Func<int> f2 = x.GetHashCode; // no error Func<object, bool> f3 = x.Equals; // no error Func<Type> f4 = x.GetType; // no error Func<int> x1 = x.GetValueOrDefault; // 1728 Func<int, int> x2 = x.GetValueOrDefault; // 1728 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,24): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault()' because it is a member of 'System.Nullable<T>' // Func<int> x1 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault()"), // (15,29): error CS1728: Cannot bind delegate to 'int?.GetValueOrDefault(int)' because it is a member of 'System.Nullable<T>' // Func<int, int> x2 = x.GetValueOrDefault; // 1728 Diagnostic(ErrorCode.ERR_DelegateOnNullable, "x.GetValueOrDefault").WithArguments("int?.GetValueOrDefault(int)") ); } [Fact, WorkItem(999399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999399")] public void CS1729ERR_BadCtorArgCount() { var text = @" class Test { static int Main() { double d = new double(4.5); // was CS0143 (Dev10) Test test1 = new Test(2); // CS1729 Test test2 = new Test(); Parent exampleParent1 = new Parent(10); // CS1729 Parent exampleParent2 = new Parent(10, 1); if (test1 == test2 & exampleParent1 == exampleParent2) {} return 1; } } public class Parent { public Parent(int i, int j) { } } public class Child : Parent { } // CS1729 public class Child2 : Parent { public Child2(int k) : base(k, 0) { } }"; var compilation = CreateCompilation(text); DiagnosticDescription[] expected = { // (21,14): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Parent.Parent(int, int)' // public class Child : Parent { } // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Child").WithArguments("i", "Parent.Parent(int, int)").WithLocation(21, 14), // (6,24): error CS1729: 'double' does not contain a constructor that takes 1 arguments // double d = new double(4.5); // was CS0143 (Dev10) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "double").WithArguments("double", "1").WithLocation(6, 24), // (7,26): error CS1729: 'Test' does not contain a constructor that takes 1 arguments // Test test1 = new Test(2); // CS1729 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("Test", "1").WithLocation(7, 26), // (9,37): error CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'Parent.Parent(int, int)' // Parent exampleParent1 = new Parent(10); // CS1729 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Parent").WithArguments("j", "Parent.Parent(int, int)").WithLocation(9, 37) }; compilation.VerifyDiagnostics(expected); compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, compilation.SyntaxTrees.Single(), filterSpanWithinTree: null, includeEarlierStages: true).Verify(expected); } [WorkItem(539631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539631")] [Fact] public void CS1729ERR_BadCtorArgCount02() { var text = @" class MyClass { int intI = 1; MyClass() { intI = 2; } //this constructor initializer MyClass(int intJ) : this(3, 4) // CS1729 { intI = intI * intJ; } } class MyBase { public int intI = 1; protected MyBase() { intI = 2; } protected MyBase(int intJ) { intI = intJ; } } class MyDerived : MyBase { MyDerived() : base(3, 4) // CS1729 { intI = intI * 2; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadCtorArgCount, Line = 32, Column = 19 }); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @" class C { public void Goo(string s = null, int x) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultValueBeforeRequiredValue, Line = 4, Column = 43 } } //sic: error on close paren ); } [WorkItem(539007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539007")] [Fact] public void DevDiv4792_OptionalBeforeParams() { var text = @" class C { public void Goo(string s = null, params int[] ints) { } } "; //no errors var comp = CreateCompilation(text); Assert.False(comp.GetDiagnostics().Any()); } [WorkItem(527351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527351")] [Fact] public void CS1738ERR_NamedArgumentSpecificationBeforeFixedArgument() { var text = @" public class C { public static int Main() { Test(age: 5,""""); return 0; } public static void Test(int age, string Name) { } }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular6); comp.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test(age: 5,""); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, @"""""").WithArguments("7.2").WithLocation(6, 21) ); } [Fact] public void CS1739ERR_BadNamedArgument() { var text = @" public class C { public static int Main() { Test(5,Nam:null); return 0; } public static void Test(int age , string Name) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact, WorkItem(866112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866112")] public void CS1739ERR_BadNamedArgument_1() { var text = @" public class C { public static void Main() { Test(1, 2, Name:3); } public static void Test(params int [] array) { } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1739, Line = 6, Column = 20 } }); } [Fact] public void CS1740ERR_DuplicateNamedArgument() { var text = @" public class C { public static int Main() { Test(age: 5, Name: ""5"", Name: """"); return 0; } public static void Test(int age, string Name) { } }"; var compilation = CSharpTestBase.CreateCompilation(text); compilation.VerifyDiagnostics( // (6,33): error CS1740: Named argument 'Name' cannot be specified multiple times // Test(age: 5, Name: "5", Name: ""); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "Name").WithArguments("Name").WithLocation(6, 33)); } [Fact] public void CS1742ERR_NamedArgumentForArray() { var text = @" public class B { static int Main() { int[] arr = { }; int s = arr[arr: 1]; s = s + 1; return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1742, Line = 7, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional() { var text = @" public class C { public static int Main() { Test(5, age: 3); return 0; } public static void Test(int age , string Name) { } }"; // CS1744: Named argument 'q' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 21 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional2() { // Unfortunately we allow "void M(params int[] x)" to be called in the expanded // form as "M(x : 123);". However, we still do not allow "M(123, x:456);". var text = @" public class C { public static void Main() { Test(5, x: 3); } public static void Test(params int[] x) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional3() { var text = @" public class C { public static void Main() { Test(5, x : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 17 } }); } [Fact] public void CS1744ERR_NamedArgumentUsedInPositional4() { var text = @" public class C { public static void Main() { Test(5, 6, 7, 8, 9, 10, z : 6); } public static void Test(int x, int y = 10, params int[] z) { } }"; // CS1744: Named argument 'z' specifies a parameter for which a positional argument has already been given. DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1744, Line = 6, Column = 33 } }); } [Fact] public void CS1746ERR_BadNamedArgumentForDelegateInvoke() { var text = @" public class C { delegate int MyDg(int age); public static int Main() { MyDg dg = new MyDg(Test); int S = dg(Ne: 3); return 0; } public static int Test(int age) { return 1; } }"; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = 1746, Line = 8, Column = 24 } }); } // [Fact()] // public void CS1752ERR_FixedNeedsLvalue() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_FixedNeedsLvalue, Line = 20, Column = 9 } } // ); // } // CS1912 --> ObjectAndCollectionInitializerTests.cs // CS1913 --> ObjectAndCollectionInitializerTests.cs // CS1914 --> ObjectAndCollectionInitializerTests.cs // CS1917 --> ObjectAndCollectionInitializerTests.cs // CS1918 --> ObjectAndCollectionInitializerTests.cs // CS1920 --> ObjectAndCollectionInitializerTests.cs // CS1921 --> ObjectAndCollectionInitializerTests.cs // CS1922 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1919ERR_UnsafeTypeInObjectCreation() { var text = @" unsafe public class C { public static int Main() { var col1 = new int*(); // CS1919 var col2 = new char*(); // CS1919 return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS1919: Unsafe type 'int*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new int*()").WithArguments("int*"), // (7,20): error CS1919: Unsafe type 'char*' cannot be used in object creation Diagnostic(ErrorCode.ERR_UnsafeTypeInObjectCreation, "new char*()").WithArguments("char*")); } [Fact] public void CS1928ERR_BadExtensionArgTypes() { var text = @"class C { static void M(float f) { f.F(); } } static class S { internal static void F(this double d) { } }"; var compilation = CreateCompilationWithMscorlib40(text, references: new[] { Net40.SystemCore }); // Previously ERR_BadExtensionArgTypes. compilation.VerifyDiagnostics( // (5,9): error CS1929: 'float' does not contain a definition for 'F' and the best extension method overload 'S.F(double)' requires a receiver of type 'double' // f.F(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "f").WithArguments("float", "F", "S.F(double)", "double").WithLocation(5, 9)); } [Fact] public void CS1929ERR_BadInstanceArgType() { var source = @"class A { } class B : A { static void M(A a) { a.E(); } } static class S { internal static void E(this B b) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }); compilation.VerifyDiagnostics( // (6,9): error CS1929: 'A' does not contain a definition for 'E' and the best extension method overload 'S.E(B)' requires a receiver of type 'B' // a.E(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "E", "S.E(B)", "B").WithLocation(6, 9) ); } [Fact] public void CS1930ERR_QueryDuplicateRangeVariable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Program { static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; var query = from num in nums let num = 3 // CS1930 select num; } } ").VerifyDiagnostics( // (10,25): error CS1930: The range variable 'num' has already been declared Diagnostic(ErrorCode.ERR_QueryDuplicateRangeVariable, "num").WithArguments("num")); } [Fact] public void CS1931ERR_QueryRangeVariableOverrides01() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int x = 1; var y = from x in Enumerable.Range(1, 100) // CS1931 select x + 1; } } ").VerifyDiagnostics( // (9,22): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // var y = from x in Enumerable.Range(1, 100) // CS1931 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x"), // (8,13): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = null select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign <null> to a range variable // let k = null Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = null").WithArguments("<null>") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = ()=>3 select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign lambda expression to a range variable // let k = ()=>3 Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = ()=>3").WithArguments("lambda expression") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue03() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = Main select i; } } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign method group to a range variable // let k = Main Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = Main").WithArguments("method group") ); } [Fact] public void CS1932ERR_QueryRangeVariableAssignedBadValue04() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { var x = from i in Enumerable.Range(1, 100) let k = M() select i; } static void M() {} } ").VerifyDiagnostics( // (8,21): error CS1932: Cannot assign void to a range variable // let k = M() Diagnostic(ErrorCode.ERR_QueryRangeVariableAssignedBadValue, "k = M()").WithArguments("void") ); } [WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")] [Fact()] public void CS1933ERR_QueryNotAllowed() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; class P { const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 static int Main() { return 1; } } ").VerifyDiagnostics( // EDMAURER now giving the more generic message CS0133 // (7,27): error CS1933: Expression cannot contain query expressions // from //Diagnostic(ErrorCode.ERR_QueryNotAllowed, "from").WithArguments()); // (7,27): error CS0133: The expression being assigned to 'P.e' must be constant // const IEnumerable e = from x in new int[] { 1, 2, 3 } select x; // CS1933 Diagnostic(ErrorCode.ERR_NotConstantExpression, "from x in new int[] { 1, 2, 3 } select x").WithArguments("P.e") ); } [Fact] public void CS1934ERR_QueryNoProviderCastable() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; using System.Collections; static class Test { public static void Main() { var list = new ArrayList(); var q = from x in list // CS1934 select x + 1; } } ").VerifyDiagnostics( // (9,27): error CS1934: Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'x'. // list Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, "list").WithArguments("System.Collections.ArrayList", "Select", "x")); } [Fact] public void CS1935ERR_QueryNoProviderStandard() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections.Generic; class Test { static int Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; IEnumerable<int> e = from n in nums where n > 3 select n; return 0; } } ").VerifyDiagnostics( // (8,40): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Where' not found. Are you missing required assembly references or a using directive for 'System.Linq'? // nums Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "nums").WithArguments("int[]", "Where")); } [Fact] public void CS1936ERR_QueryNoProvider() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { object obj = null; IEnumerable e = from x in obj // CS1936 select x; return 0; } } ").VerifyDiagnostics( // (10,35): error CS1936: Could not find an implementation of the query pattern for source type 'object'. 'Select' not found. // obj Diagnostic(ErrorCode.ERR_QueryNoProvider, "obj").WithArguments("object", "Select")); } [Fact] public void CS1936ERR_QueryNoProvider01() { var program = @" class X { internal X Cast<T>() { return this; } } class Program { static void Main() { var xx = new X(); var q3 = from int x in xx select x; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics( // (11,32): error CS1936: Could not find an implementation of the query pattern for source type 'X'. 'Select' not found. // var q3 = from int x in xx select x; Diagnostic(ErrorCode.ERR_QueryNoProvider, "xx").WithArguments("X", "Select") ); } [Fact] public void CS1937ERR_QueryOuterKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on b equals 5 // CS1937 select a + b; } } ").VerifyDiagnostics( // (11,42): error CS1937: The name 'b' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on b equals 5 // CS1937 Diagnostic(ErrorCode.ERR_QueryOuterKey, "b").WithArguments("b") ); } [Fact] public void CS1938ERR_QueryInnerKey() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { static void Main() { int[] sourceA = { 1, 2, 3, 4, 5 }; int[] sourceB = { 3, 4, 5, 6, 7 }; var query = from a in sourceA join b in sourceB on 5 equals a // CS1938 select a + b; } } ").VerifyDiagnostics( // (11,51): error CS1938: The name 'a' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // join b in sourceB on 5 equals a // CS1938 Diagnostic(ErrorCode.ERR_QueryInnerKey, "a").WithArguments("a") ); } [Fact] public void CS1939ERR_QueryOutRefRangeVariable() { var text = @" using System.Linq; class Test { public static int F(ref int i) { return i; } public static void Main() { var list = new int[] { 0, 1, 2, 3, 4, 5 }; var q = from x in list let k = x select Test.F(ref x); // CS1939 } } "; CreateCompilation(text).VerifyDiagnostics( // (13,35): error CS1939: Cannot pass the range variable 'x' as an out or ref parameter // select Test.F(ref x); // CS1939 Diagnostic(ErrorCode.ERR_QueryOutRefRangeVariable, "x").WithArguments("x")); } [Fact] public void CS1940ERR_QueryMultipleProviders() { var text = @"using System; class Test { public delegate int Dele(int x); int num = 0; public int Select(Func<int, int> d) { return d(this.num); } public int Select(Dele d) { return d(this.num) + 1; } public static void Main() { var q = from x in new Test() select x; // CS1940 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (18,17): error CS1940: Multiple implementations of the query pattern were found for source type 'Test'. Ambiguous call to 'Select'. // select Diagnostic(ErrorCode.ERR_QueryMultipleProviders, "select x").WithArguments("Test", "Select") ); } [Fact] public void CS1941ERR_QueryTypeInferenceFailedMulti() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Collections; using System.Linq; class Test { static int Main() { var nums = new int[] { 1, 2, 3, 4, 5, 6 }; var words = new string[] { ""lake"", ""mountain"", ""sky"" }; IEnumerable e = from n in nums join w in words on n equals w // CS1941 select w; return 0; } } ").VerifyDiagnostics( // (11,25): error CS1941: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. // join Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedMulti, "join").WithArguments("join", "Join")); } [Fact] public void CS1942ERR_QueryTypeInferenceFailed() { var text = @" using System; class Q { public Q Select<T,U>(Func<int, int> func) { return this; } } class Program { static void Main(string[] args) { var x = from i in new Q() select i; //CS1942 } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,17): error CS1942: The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'. // select i; //CS1942 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailed, "select").WithArguments("select", "Select") ); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { class TestClass { } static void Main() { int[] nums = { 0, 1, 2, 3, 4, 5 }; TestClass tc = new TestClass(); var x = from n in nums from s in tc // CS1943 select n + s; } } ").VerifyDiagnostics( // (13,27): error CS1943: An expression of type 'Test.TestClass' is not allowed in a subsequent from clause in a query expression with source type 'int[]'. Type inference failed in the call to 'SelectMany'. // tc Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "tc").WithArguments("Test.TestClass", "int[]", "SelectMany")); } [Fact] public void CS1943ERR_QueryTypeInferenceFailedSelectMany02() { CreateCompilationWithMscorlib40AndSystemCore(@" using System; class Test { class F1 { public F1 SelectMany<T, U>(Func<int, F1> func1, Func<int, int> func2) { return this; } } static void Main() { F1 f1 = new F1(); var x = from f in f1 from g in 3 select f + g; } } ").VerifyDiagnostics( // (14,23): error CS1943: An expression of type 'int' is not allowed in a subsequent from clause in a query expression with source type 'Test.F1'. Type inference failed in the call to 'SelectMany'. // from g in 3 Diagnostic(ErrorCode.ERR_QueryTypeInferenceFailedSelectMany, "3").WithArguments("int", "Test.F1", "SelectMany").WithLocation(14, 23) ); } [Fact, WorkItem(546510, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546510")] public void CS1944ERR_ExpressionTreeContainsPointerOp() { var text = @" using System; using System.Linq.Expressions; unsafe class Test { public delegate int* D(int i); static void Main() { Expression<D> tree = x => &x; // CS1944 Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; } } "; //Assert.Equal("", text); CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,35): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<D> tree = x => &x; // CS1944 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x"), // (11,68): error CS1944: An expression tree may not contain an unsafe pointer operation // Expression<Func<int, int*[]>> testExpr = x => new int*[] { &x }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPointerOp, "&x") ); } [Fact] public void CS1945ERR_ExpressionTreeContainsAnonymousMethod() { var text = @" using System; using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,61): error CS1945: An expression tree may not contain an anonymous method expression // Expression<Func<int, Func<int, bool>>> tree = (x => delegate(int i) { return true; }); // CS1945 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAnonymousMethod, "delegate(int i) { return true; }") ); } [Fact] public void CS1946ERR_AnonymousMethodToExpressionTree() { var text = @" using System.Linq.Expressions; public delegate void D(); class Test { static void Main() { Expression<D> tree = delegate() { }; //CS1946 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,30): error CS1946: An anonymous method expression cannot be converted to an expression tree // Expression<D> tree = delegate() { }; //CS1946 Diagnostic(ErrorCode.ERR_AnonymousMethodToExpressionTree, "delegate() { }") ); } [Fact] public void CS1947ERR_QueryRangeVariableReadOnly() { var program = @" using System.Linq; class Test { static void Main() { int[] array = new int[] { 1, 2, 3, 4, 5 }; var x = from i in array let k = i select i = 5; // CS1947 x.ToList(); } } "; CreateCompilation(program).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "i").WithArguments("i")); } [Fact] public void CS1948ERR_QueryRangeVariableSameAsTypeParam() { CreateCompilationWithMscorlib40AndSystemCore(@" using System.Linq; class Test { public void TestMethod<T>(T t) { var x = from T in Enumerable.Range(1, 100) // CS1948 select T; } public static void Main() { } } ").VerifyDiagnostics( // (8,17): error CS1948: The range variable 'T' cannot have the same name as a method type parameter // T Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "T").WithArguments("T")); } [Fact] public void CS1949ERR_TypeVarNotFoundRangeVariable() { var text = @"using System.Linq; class Test { static void Main() { var x = from var i in Enumerable.Range(1, 100) // CS1949 select i; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,22): error CS1949: The contextual keyword 'var' cannot be used in a range variable declaration // var x = from var i in Enumerable.Range(1, 100) // CS1949 Diagnostic(ErrorCode.ERR_TypeVarNotFoundRangeVariable, "var") ); } // CS1950 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1951ERR_ByRefParameterInExpressionTree() { var text = @" public delegate int TestDelegate(ref int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,75): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 75) ); } [Fact] public void CS1951ERR_InParameterInExpressionTree() { var text = @" public delegate int TestDelegate(in int i); class Test { static void Main() { System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (7,74): error CS1951: An expression tree lambda may not contain a ref, in or out parameter // System.Linq.Expressions.Expression<TestDelegate> tree1 = (in int x) => x; // CS1951 Diagnostic(ErrorCode.ERR_ByRefParameterInExpressionTree, "x").WithLocation(7, 74) ); } [Fact] public void CS1952ERR_VarArgsInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class Test { public static int M(__arglist) { return 1; } static int Main() { Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (14,52): error CS1952: An expression tree lambda may not contain a method with variable arguments // Expression<Func<int, int>> f = x => Test.M(__arglist(x)); // CS1952 Diagnostic(ErrorCode.ERR_VarArgsInExpressionTree, "__arglist(x)") ); } [WorkItem(864605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/864605")] [Fact] public void CS1953ERR_MemGroupInExpressionTree() { var text = @" using System; using System.Linq.Expressions; class CS1953 { public static void Main() { double num = 10; Expression<Func<bool>> testExpr = () => num.GetType is int; // CS0837 } }"; // Used to be CS1953, but now a method group in an is expression is illegal anyway. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (10,21): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // () => num.GetType is int; // CS1953 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "num.GetType is int").WithLocation(10, 21)); } // CS1954 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1955ERR_NonInvocableMemberCalled() { var text = @" namespace CompilerError1955 { class ClassA { public int x = 100; public int X { get { return x; } set { x = value; } } } class Test { static void Main() { ClassA a = new ClassA(); System.Console.WriteLine(a.x()); // CS1955 System.Console.WriteLine(a.X()); // CS1955 } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 19, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInvocableMemberCalled, Line = 20, Column = 40 }}); } // CS1958 --> ObjectAndCollectionInitializerTests.cs [Fact] public void CS1959ERR_InvalidConstantDeclarationType() { var text = @" class Program { static void Test<T>() where T : class { const T x = null; // CS1959 } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,25): error CS1959: 'x' is of type 'T'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. // const T x = null; // CS1959 Diagnostic(ErrorCode.ERR_InvalidConstantDeclarationType, "null").WithArguments("x", "T") ); } /// <summary> /// Test the different contexts in which CS1961 can be seen. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Contexts() { var text = @" interface IContexts<in TIn, out TOut, TInv> { #region In TIn Property1In { set; } TIn Property2In { get; } //CS1961 on ""TIn"" TIn Property3In { get; set; } //CS1961 on ""TIn"" int this[TIn arg, char filler, char indexer1In] { get; } TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on ""TIn"" int this[TIn arg, bool filler, char indexer3In] { set; } TIn this[int arg, bool[] filler, char indexer4In] { set; } int this[TIn arg, long filler, char indexer5In] { get; set; } TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on ""TIn"" int Method1In(TIn p); TIn Method2In(); //CS1961 on ""TIn"" int Method3In(out TIn p); //CS1961 on ""TIn"" int Method4In(ref TIn p); //CS1961 on ""TIn"" event DOut<TIn> Event1In; #endregion In #region Out TOut Property1Out { set; } //CS1961 on ""TOut"" TOut Property2Out { get; } TOut Property3Out { get; set; } //CS1961 on ""TOut"" int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on ""TOut"" TOut this[int arg, char[] filler, bool indexer2Out] { get; } int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on ""TOut"" TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on ""TOut"" int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on ""TOut"" TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on ""TOut"" long Method1Out(TOut p); //CS1961 on ""TOut"" TOut Method2Out(); long Method3Out(out TOut p); //CS1961 on ""TOut"" (sic: out params have to be input-safe) long Method4Out(ref TOut p); //CS1961 on ""TOut"" event DOut<TOut> Event1Out; //CS1961 on ""TOut"" #endregion Out #region Inv TInv Property1Inv { set; } TInv Property2Inv { get; } TInv Property3Inv { get; set; } int this[TInv arg, char filler, long indexer1Inv] { get; } TInv this[int arg, char[] filler, long indexer2Inv] { get; } int this[TInv arg, bool filler, long indexer3Inv] { set; } TInv this[int arg, bool[] filler, long indexer4Inv] { set; } int this[TInv arg, long filler, long indexer5Inv] { get; set; } TInv this[int arg, long[] filler, long indexer6Inv] { get; set; } long Method1Inv(TInv p); TInv Method2Inv(); long Method3Inv(out TInv p); long Method4Inv(ref TInv p); event DOut<TInv> Event1Inv; #endregion Inv } delegate void DOut<out T>(); //for event types - should preserve the variance of the type arg "; CreateCompilation(text).VerifyDiagnostics( // (6,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Property2In'. 'TIn' is contravariant. // TIn Property2In { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property2In", "TIn", "contravariant", "covariantly").WithLocation(6, 5), // (7,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3In'. 'TIn' is contravariant. // TIn Property3In { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Property3In", "TIn", "contravariant", "invariantly").WithLocation(7, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, char[], char]'. 'TIn' is contravariant. // TIn this[int arg, char[] filler, char indexer2In] { get; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, char[], char]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (14,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], char]'. 'TIn' is contravariant. // TIn this[int arg, long[] filler, char indexer6In] { get; set; } //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], char]", "TIn", "contravariant", "invariantly").WithLocation(14, 5), // (17,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IContexts<TIn, TOut, TInv>.Method2In()'. 'TIn' is contravariant. // TIn Method2In(); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method2In()", "TIn", "contravariant", "covariantly").WithLocation(17, 5), // (18,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3In(out TIn)'. 'TIn' is contravariant. // int Method3In(out TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method3In(out TIn)", "TIn", "contravariant", "invariantly").WithLocation(18, 23), // (19,23): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4In(ref TIn)'. 'TIn' is contravariant. // int Method4In(ref TIn p); //CS1961 on "TIn" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IContexts<TIn, TOut, TInv>.Method4In(ref TIn)", "TIn", "contravariant", "invariantly").WithLocation(19, 23), // (25,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Property1Out'. 'TOut' is covariant. // TOut Property1Out { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property1Out", "TOut", "covariant", "contravariantly").WithLocation(25, 5), // (27,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Property3Out'. 'TOut' is covariant. // TOut Property3Out { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Property3Out", "TOut", "covariant", "invariantly").WithLocation(27, 5), // (29,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, char, bool]'. 'TOut' is covariant. // int this[TOut arg, char filler, bool indexer1Out] { get; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, char, bool]", "TOut", "covariant", "contravariantly").WithLocation(29, 14), // (31,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]'. 'TOut' is covariant. // int this[TOut arg, bool filler, bool indexer3Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, bool, bool]", "TOut", "covariant", "contravariantly").WithLocation(31, 14), // (32,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, bool[], bool]'. 'TOut' is covariant. // TOut this[int arg, bool[] filler, bool indexer4Out] { set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, bool[], bool]", "TOut", "covariant", "contravariantly").WithLocation(32, 5), // (33,14): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.this[TOut, long, bool]'. 'TOut' is covariant. // int this[TOut arg, long filler, bool indexer5Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[TOut, long, bool]", "TOut", "covariant", "contravariantly").WithLocation(33, 14), // (34,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.this[int, long[], bool]'. 'TOut' is covariant. // TOut this[int arg, long[] filler, bool indexer6Out] { get; set; } //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.this[int, long[], bool]", "TOut", "covariant", "invariantly").WithLocation(34, 5), // (36,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Method1Out(TOut)'. 'TOut' is covariant. // long Method1Out(TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method1Out(TOut)", "TOut", "covariant", "contravariantly").WithLocation(36, 21), // (38,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method3Out(out TOut)'. 'TOut' is covariant. // long Method3Out(out TOut p); //CS1961 on "TOut" (sic: out params have to be input-safe) Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method3Out(out TOut)", "TOut", "covariant", "invariantly").WithLocation(38, 25), // (39,25): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)'. 'TOut' is covariant. // long Method4Out(ref TOut p); //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IContexts<TIn, TOut, TInv>.Method4Out(ref TOut)", "TOut", "covariant", "invariantly").WithLocation(39, 25), // (41,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IContexts<TIn, TOut, TInv>.Event1Out'. 'TOut' is covariant. // event DOut<TOut> Event1Out; //CS1961 on "TOut" Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event1Out").WithArguments("IContexts<TIn, TOut, TInv>.Event1Out", "TOut", "covariant", "contravariantly").WithLocation(41, 22)); } /// <summary> /// Test all of the contexts that require output safety. /// Note: some also require input safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_OutputUnsafe() { var text = @" interface IOutputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { get; } TInv this[long[] Indexer1Good] { get; } TInv Method1Good(); TIn Property1Bad { get; } TIn this[char[] Indexer1Bad] { get; } TIn Method1Bad(); #endregion Case 1 #region Case 2: array of output-unsafe TInv[] Property2Good { get; } TInv[] this[long[,] Indexer2Good] { get; } TInv[] Method2Good(); TIn[] Property2Bad { get; } TIn[] this[char[,] Indexer2Bad] { get; } TIn[] Method2Bad(); #endregion Case 2 #region Case 3: constructed with output-unsafe type arg in covariant slot IOut<TInv> Property3Good { get; } IOut<TInv> this[long[,,] Indexer3Good] { get; } IOut<TInv> Method3Good(); IOut<TIn> Property3Bad { get; } IOut<TIn> this[char[,,] Indexer3Bad] { get; } IOut<TIn> Method3Bad(); #endregion Case 3 #region Case 4: constructed with output-unsafe type arg in invariant slot IInv<TInv> Property4Good { get; } IInv<TInv> this[long[,,,] Indexer4Good] { get; } IInv<TInv> Method4Good(); IInv<TIn> Property4Bad { get; } IInv<TIn> this[char[,,,] Indexer4Bad] { get; } IInv<TIn> Method4Bad(); #endregion Case 4 #region Case 5: constructed with input-unsafe (sic) type arg in contravariant slot IIn<TInv> Property5Good { get; } IIn<TInv> this[long[,,,,] Indexer5Good] { get; } IIn<TInv> Method5Good(); IIn<TOut> Property5Bad { get; } IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } IIn<TOut> Method5Bad(); #endregion Case 5 #region Case 6: constructed with input-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { get; } IInv<TInv> this[long[,,,,,] Indexer6Good] { get; } IInv<TInv> Method6Good(); IInv<TOut> Property6Bad { get; } IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } IInv<TOut> Method6Bad(); #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (9,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TIn' is contravariant. // TIn Property1Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property1Bad", "TIn", "contravariant", "covariantly").WithLocation(9, 5), // (10,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TIn' is contravariant. // TIn this[char[] Indexer1Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[]]", "TIn", "contravariant", "covariantly").WithLocation(10, 5), // (11,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()'. 'TIn' is contravariant. // TIn Method1Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method1Bad()", "TIn", "contravariant", "covariantly").WithLocation(11, 5), // (19,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TIn' is contravariant. // TIn[] Property2Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property2Bad", "TIn", "contravariant", "covariantly").WithLocation(19, 5), // (20,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TIn' is contravariant. // TIn[] this[char[,] Indexer2Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TIn", "contravariant", "covariantly").WithLocation(20, 5), // (21,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()'. 'TIn' is contravariant. // TIn[] Method2Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn[]").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method2Bad()", "TIn", "contravariant", "covariantly").WithLocation(21, 5), // (29,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TIn' is contravariant. // IOut<TIn> Property3Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property3Bad", "TIn", "contravariant", "covariantly").WithLocation(29, 5), // (30,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TIn' is contravariant. // IOut<TIn> this[char[,,] Indexer3Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(30, 5), // (31,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()'. 'TIn' is contravariant. // IOut<TIn> Method3Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method3Bad()", "TIn", "contravariant", "covariantly").WithLocation(31, 5), // (39,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TIn' is contravariant. // IInv<TIn> Property4Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property4Bad", "TIn", "contravariant", "invariantly").WithLocation(39, 5), // (40,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,] Indexer4Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(40, 5), // (41,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()'. 'TIn' is contravariant. // IInv<TIn> Method4Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method4Bad()", "TIn", "contravariant", "invariantly").WithLocation(41, 5), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TOut' is covariant. // IIn<TOut> Property5Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property5Bad", "TOut", "covariant", "contravariantly").WithLocation(49, 5), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TOut' is covariant. // IIn<TOut> this[char[,,,,] Indexer5Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(50, 5), // (51,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()'. 'TOut' is covariant. // IIn<TOut> Method5Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method5Bad()", "TOut", "covariant", "contravariantly").WithLocation(51, 5), // (59,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TOut' is covariant. // IInv<TOut> Property6Bad { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Property6Bad", "TOut", "covariant", "invariantly").WithLocation(59, 5), // (60,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,,,] Indexer6Bad] { get; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(60, 5), // (61,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()'. 'TOut' is covariant. // IInv<TOut> Method6Bad(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IOutputUnsafe<TIn, TOut, TInv>.Method6Bad()", "TOut", "covariant", "invariantly").WithLocation(61, 5)); } /// <summary> /// Test all of the contexts that require input safety. /// Note: some also require output safety. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_InputUnsafe() { var text = @" interface IInputUnsafe<in TIn, out TOut, TInv> { #region Case 1: contravariant type parameter TInv Property1Good { set; } TInv this[long[] Indexer1GoodA] { set; } long this[long[] Indexer1GoodB, TInv p] { set; } long Method1Good(TInv p); TOut Property1Bad { set; } TOut this[char[] Indexer1BadA] { set; } long this[char[] Indexer1BadB, TOut p] { set; } long Method1Bad(TOut p); #endregion Case 1 #region Case 2: array of input-unsafe TInv[] Property2Good { set; } TInv[] this[long[,] Indexer2GoodA] { set; } long this[long[,] Indexer2GoodB, TInv[] p] { set; } long Method2Good(TInv[] p); TOut[] Property2Bad { set; } TOut[] this[char[,] Indexer2BadA] { set; } long this[char[,] Indexer2BadB, TOut[] p] { set; } long Method2Bad(TOut[] p); #endregion Case 2 #region Case 3: constructed with input-unsafe type arg in covariant (sic: not flipped) slot IOut<TInv> Property3Good { set; } IOut<TInv> this[long[,,] Indexer3GoodA] { set; } long this[long[,,] Indexer3GoodB, IOut<TInv> p] { set; } long Method3Good(IOut<TInv> p); event DOut<TInv> Event3Good; IOut<TOut> Property3Bad { set; } IOut<TOut> this[char[,,] Indexer3BadA] { set; } long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } long Method3Bad(IOut<TOut> p); event DOut<TOut> Event3Bad; #endregion Case 3 #region Case 4: constructed with input-unsafe type arg in invariant slot IInv<TInv> Property4Good { set; } IInv<TInv> this[long[,,,] Indexer4GoodA] { set; } long this[long[,,,] Indexer4GoodB, IInv<TInv> p] { set; } long Method4Good(IInv<TInv> p); event DInv<TInv> Event4Good; IInv<TOut> Property4Bad { set; } IInv<TOut> this[char[,,,] Indexer4BadA] { set; } long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } long Method4Bad(IInv<TOut> p); event DInv<TOut> Event4Bad; #endregion Case 4 #region Case 5: constructed with output-unsafe (sic) type arg in contravariant (sic: not flipped) slot IIn<TInv> Property5Good { set; } IIn<TInv> this[long[,,,,] Indexer5GoodA] { set; } long this[long[,,,,] Indexer5GoodB, IIn<TInv> p] { set; } long Method5Good(IIn<TInv> p); event DIn<TInv> Event5Good; IIn<TIn> Property5Bad { set; } IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } long Method5Bad(IIn<TIn> p); event DIn<TIn> Event5Bad; #endregion Case 5 #region Case 6: constructed with output-unsafe (sic) type arg in invariant slot IInv<TInv> Property6Good { set; } IInv<TInv> this[long[,,,,,] Indexer6GoodA] { set; } long this[long[,,,,,] Indexer6GoodB, IInv<TInv> p] { set; } long Method6Good(IInv<TInv> p); event DInv<TInv> Event6Good; IInv<TIn> Property6Bad { set; } IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } long Method6Bad(IInv<TIn> p); event DInv<TIn> Event6Bad; #endregion Case 6 } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { } delegate void DIn<in T>(); delegate void DOut<out T>(); delegate void DInv<T>(); "; CreateCompilation(text).VerifyDiagnostics( // (11,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[]]'. 'TOut' is covariant. // TOut this[char[] Indexer1BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[]]", "TOut", "covariant", "contravariantly").WithLocation(11, 5), // (12,36): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]'. 'TOut' is covariant. // long this[char[] Indexer1BadB, TOut p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[], TOut]", "TOut", "covariant", "contravariantly").WithLocation(12, 36), // (23,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]'. 'TOut' is covariant. // TOut[] this[char[,] Indexer2BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*]]", "TOut", "covariant", "contravariantly").WithLocation(23, 5), // (24,37): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]'. 'TOut' is covariant. // long this[char[,] Indexer2BadB, TOut[] p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*], TOut[]]", "TOut", "covariant", "contravariantly").WithLocation(24, 37), // (36,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]'. 'TOut' is covariant. // IOut<TOut> this[char[,,] Indexer3BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*]]", "TOut", "covariant", "contravariantly").WithLocation(36, 5), // (37,38): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]'. 'TOut' is covariant. // long this[char[,,] Indexer3BadB, IOut<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*], IOut<TOut>]", "TOut", "covariant", "contravariantly").WithLocation(37, 38), // (50,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]'. 'TOut' is covariant. // IInv<TOut> this[char[,,,] Indexer4BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*]]", "TOut", "covariant", "invariantly").WithLocation(50, 5), // (51,39): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]'. 'TOut' is covariant. // long this[char[,,,] Indexer4BadB, IInv<TOut> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*], IInv<TOut>]", "TOut", "covariant", "invariantly").WithLocation(51, 39), // (64,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]'. 'TIn' is contravariant. // IIn<TIn> this[char[,,,,] Indexer5BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*]]", "TIn", "contravariant", "covariantly").WithLocation(64, 5), // (65,40): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,] Indexer5BadB, IIn<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*], IIn<TIn>]", "TIn", "contravariant", "covariantly").WithLocation(65, 40), // (78,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]'. 'TIn' is contravariant. // IInv<TIn> this[char[,,,,,] Indexer6BadA] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*]]", "TIn", "contravariant", "invariantly").WithLocation(78, 5), // (79,41): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]'. 'TIn' is contravariant. // long this[char[,,,,,] Indexer6BadB, IInv<TIn> p] { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.this[char[*,*,*,*,*,*], IInv<TIn>]", "TIn", "contravariant", "invariantly").WithLocation(79, 41), // (10,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property1Bad'. 'TOut' is covariant. // TOut Property1Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property1Bad", "TOut", "covariant", "contravariantly").WithLocation(10, 5), // (13,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)'. 'TOut' is covariant. // long Method1Bad(TOut p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method1Bad(TOut)", "TOut", "covariant", "contravariantly").WithLocation(13, 21), // (22,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property2Bad'. 'TOut' is covariant. // TOut[] Property2Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property2Bad", "TOut", "covariant", "contravariantly").WithLocation(22, 5), // (25,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])'. 'TOut' is covariant. // long Method2Bad(TOut[] p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut[]").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method2Bad(TOut[])", "TOut", "covariant", "contravariantly").WithLocation(25, 21), // (35,5): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property3Bad'. 'TOut' is covariant. // IOut<TOut> Property3Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property3Bad", "TOut", "covariant", "contravariantly").WithLocation(35, 5), // (38,21): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)'. 'TOut' is covariant. // long Method3Bad(IOut<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IOut<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method3Bad(IOut<TOut>)", "TOut", "covariant", "contravariantly").WithLocation(38, 21), // (39,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event3Bad'. 'TOut' is covariant. // event DOut<TOut> Event3Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event3Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event3Bad", "TOut", "covariant", "contravariantly").WithLocation(39, 22), // (49,5): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property4Bad'. 'TOut' is covariant. // IInv<TOut> Property4Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property4Bad", "TOut", "covariant", "invariantly").WithLocation(49, 5), // (52,21): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)'. 'TOut' is covariant. // long Method4Bad(IInv<TOut> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TOut>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method4Bad(IInv<TOut>)", "TOut", "covariant", "invariantly").WithLocation(52, 21), // (53,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event4Bad'. 'TOut' is covariant. // event DInv<TOut> Event4Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event4Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event4Bad", "TOut", "covariant", "invariantly").WithLocation(53, 22), // (63,5): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property5Bad'. 'TIn' is contravariant. // IIn<TIn> Property5Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property5Bad", "TIn", "contravariant", "covariantly").WithLocation(63, 5), // (66,21): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)'. 'TIn' is contravariant. // long Method5Bad(IIn<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method5Bad(IIn<TIn>)", "TIn", "contravariant", "covariantly").WithLocation(66, 21), // (67,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event5Bad'. 'TIn' is contravariant. // event DIn<TIn> Event5Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event5Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event5Bad", "TIn", "contravariant", "covariantly").WithLocation(67, 20), // (77,5): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Property6Bad'. 'TIn' is contravariant. // IInv<TIn> Property6Bad { set; } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Property6Bad", "TIn", "contravariant", "invariantly").WithLocation(77, 5), // (80,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)'. 'TIn' is contravariant. // long Method6Bad(IInv<TIn> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInv<TIn>").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Method6Bad(IInv<TIn>)", "TIn", "contravariant", "invariantly").WithLocation(80, 21), // (81,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'IInputUnsafe<TIn, TOut, TInv>.Event6Bad'. 'TIn' is contravariant. // event DInv<TIn> Event6Bad; Diagnostic(ErrorCode.ERR_UnexpectedVariance, "Event6Bad").WithArguments("IInputUnsafe<TIn, TOut, TInv>.Event6Bad", "TIn", "contravariant", "invariantly").WithLocation(81, 21)); } /// <summary> /// Test output-safety checks on base interfaces. /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_BaseInterfaces() { var text = @" interface IBaseInterfaces<in TIn, out TOut, TInv> : IIn<TOut>, IOut<TIn>, IInv<TInv> { } interface IIn<in T> { } interface IOut<out T> { } interface IInv<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'IIn<TOut>'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("IIn<TOut>", "TOut", "covariant", "contravariantly"), // (2,30): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'IOut<TIn>'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("IOut<TIn>", "TIn", "contravariant", "covariantly")); } /// <summary> /// Test all type parameter/type argument combinations. /// | Type Arg Covariant | Type Arg Contravariant | Type Arg Invariant /// -------------------------+----------------------+------------------------+-------------------- /// Type Param Covariant | Covariant | Contravariant | Invariant /// Type Param Contravariant | Contravariant | Covariant | Invariant /// Type Param Invariant | Error | Error | Invariant /// </summary> [Fact] public void CS1961ERR_UnexpectedVariance_Generics() { var text = @" interface IOutputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { ICovariant<TInputUnsafe> OutputUnsafe1(); ICovariant<TOutputUnsafe> OutputUnsafe2(); ICovariant<TInvariant> OutputUnsafe3(); IContravariant<TInputUnsafe> OutputUnsafe4(); IContravariant<TOutputUnsafe> OutputUnsafe5(); IContravariant<TInvariant> OutputUnsafe6(); IInvariant<TInputUnsafe> OutputUnsafe7(); IInvariant<TOutputUnsafe> OutputUnsafe8(); IInvariant<TInvariant> OutputUnsafe9(); } interface IInputUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ICovariant<TInputUnsafe> p); void InputUnsafe2(ICovariant<TOutputUnsafe> p); void InputUnsafe3(ICovariant<TInvariant> p); void InputUnsafe4(IContravariant<TInputUnsafe> p); void InputUnsafe5(IContravariant<TOutputUnsafe> p); void InputUnsafe6(IContravariant<TInvariant> p); void InputUnsafe7(IInvariant<TInputUnsafe> p); void InputUnsafe8(IInvariant<TOutputUnsafe> p); void InputUnsafe9(IInvariant<TInvariant> p); } interface IBothUnsafeTable<out TInputUnsafe, in TOutputUnsafe, TInvariant> { void InputUnsafe1(ref ICovariant<TInputUnsafe> p); void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); void InputUnsafe3(ref ICovariant<TInvariant> p); void InputUnsafe4(ref IContravariant<TInputUnsafe> p); void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); void InputUnsafe6(ref IContravariant<TInvariant> p); void InputUnsafe7(ref IInvariant<TInputUnsafe> p); void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); void InputUnsafe9(ref IInvariant<TInvariant> p); } interface ICovariant<out T> { } interface IContravariant<in T> { } interface IInvariant<T> { }"; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()'. 'TOutputUnsafe' is contravariant. // ICovariant<TOutputUnsafe> OutputUnsafe2(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe2()", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(5, 5), // (8,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()'. 'TInputUnsafe' is covariant. // IContravariant<TInputUnsafe> OutputUnsafe4(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe4()", "TInputUnsafe", "covariant", "contravariantly").WithLocation(8, 5), // (12,5): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()'. 'TInputUnsafe' is covariant. // IInvariant<TInputUnsafe> OutputUnsafe7(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe7()", "TInputUnsafe", "covariant", "invariantly").WithLocation(12, 5), // (13,5): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()'. 'TOutputUnsafe' is contravariant. // IInvariant<TOutputUnsafe> OutputUnsafe8(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IOutputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.OutputUnsafe8()", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(13, 5), // (19,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be contravariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "contravariantly").WithLocation(19, 23), // (24,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be covariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "covariantly").WithLocation(24, 23), // (27,23): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(27, 23), // (28,23): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IInputUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(28, 23), // Dev10 doesn't say "must be invariantly valid" for ref params - it lists whichever check fails first. This approach seems nicer. // (34,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe1(ref ICovariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe1(ref ICovariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(34, 27), // (35,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe2(ref ICovariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ICovariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe2(ref ICovariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(35, 27), // (38,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe4(ref IContravariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe4(ref IContravariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(38, 27), // (39,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe5(ref IContravariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IContravariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe5(ref IContravariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(39, 27), // (42,27): error CS1961: Invalid variance: The type parameter 'TInputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)'. 'TInputUnsafe' is covariant. // void InputUnsafe7(ref IInvariant<TInputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TInputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe7(ref IInvariant<TInputUnsafe>)", "TInputUnsafe", "covariant", "invariantly").WithLocation(42, 27), // (43,27): error CS1961: Invalid variance: The type parameter 'TOutputUnsafe' must be invariantly valid on 'IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)'. 'TOutputUnsafe' is contravariant. // void InputUnsafe8(ref IInvariant<TOutputUnsafe> p); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IInvariant<TOutputUnsafe>").WithArguments("IBothUnsafeTable<TInputUnsafe, TOutputUnsafe, TInvariant>.InputUnsafe8(ref IInvariant<TOutputUnsafe>)", "TOutputUnsafe", "contravariant", "invariantly").WithLocation(43, 27)); } [Fact] public void CS1961ERR_UnexpectedVariance_DelegateInvoke() { var text = @" delegate TIn D1<in TIn>(); //CS1961 delegate TOut D2<out TOut>(); delegate T D3<T>(); delegate void D4<in TIn>(TIn p); delegate void D5<out TOut>(TOut p); //CS1961 delegate void D6<T>(T p); delegate void D7<in TIn>(ref TIn p); //CS1961 delegate void D8<out TOut>(ref TOut p); //CS1961 delegate void D9<T>(ref T p); delegate void D10<in TIn>(out TIn p); //CS1961 delegate void D11<out TOut>(out TOut p); //CS1961 delegate void D12<T>(out T p); "; CreateCompilation(text).VerifyDiagnostics( // (2,20): error CS1961: Invalid variance: The type parameter 'TIn' must be covariantly valid on 'D1<TIn>.Invoke()'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D1<TIn>.Invoke()", "TIn", "contravariant", "covariantly"), // (7,22): error CS1961: Invalid variance: The type parameter 'TOut' must be contravariantly valid on 'D5<TOut>.Invoke(TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D5<TOut>.Invoke(TOut)", "TOut", "covariant", "contravariantly"), // (10,21): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D7<TIn>.Invoke(ref TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D7<TIn>.Invoke(ref TIn)", "TIn", "contravariant", "invariantly"), // (11,22): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D8<TOut>.Invoke(ref TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D8<TOut>.Invoke(ref TOut)", "TOut", "covariant", "invariantly"), // (14,22): error CS1961: Invalid variance: The type parameter 'TIn' must be invariantly valid on 'D10<TIn>.Invoke(out TIn)'. 'TIn' is contravariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TIn").WithArguments("D10<TIn>.Invoke(out TIn)", "TIn", "contravariant", "invariantly"), // (15,23): error CS1961: Invalid variance: The type parameter 'TOut' must be invariantly valid on 'D11<TOut>.Invoke(out TOut)'. 'TOut' is covariant. Diagnostic(ErrorCode.ERR_UnexpectedVariance, "TOut").WithArguments("D11<TOut>.Invoke(out TOut)", "TOut", "covariant", "invariantly")); } [Fact] public void CS1962ERR_BadDynamicTypeof() { var text = @" public class C { public static int Main() { dynamic S = typeof(dynamic); return 0; } public static int Test(int age) { return 1; } }"; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS1962: The typeof operator cannot be used on the dynamic type Diagnostic(ErrorCode.ERR_BadDynamicTypeof, "typeof(dynamic)")); } [Fact] [WorkItem(54804, "https://github.com/dotnet/roslyn/issues/54804")] public void BadNestedTypeof() { var source = @" #nullable enable using System; using System.Collections.Generic; var x = typeof(List<dynamic>); // 1 x = typeof(nint); // 2 x = typeof(List<nint>); // 3 x = typeof(List<string?>); // 4 x = typeof((int a, int b)); // 5 x = typeof((int a, string? b)); // 6 x = typeof(ValueTuple<int, int>); // ok "; CreateCompilation(source).VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.DebugExe.WithWarningLevel(5)).VerifyDiagnostics(); } // CS1963ERR_ExpressionTreeContainsDynamicOperation --> SyntaxBinderTests [Fact] public void CS1964ERR_BadDynamicConversion() { var text = @" class A { public static implicit operator dynamic(A a) { return a; } public static implicit operator A(dynamic a) { return a; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (9,37): error CS1964: 'A.implicit operator A(dynamic)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "A").WithArguments("A.implicit operator A(dynamic)"), // (4,37): error CS1964: 'A.implicit operator dynamic(A)': user-defined conversions to or from the dynamic type are not allowed Diagnostic(ErrorCode.ERR_BadDynamicConversion, "dynamic").WithArguments("A.implicit operator dynamic(A)")); } // CS1969ERR_DynamicRequiredTypesMissing -> CodeGen_DynamicTests.Missing_* // CS1970ERR_ExplicitDynamicAttr --> AttributeTests_Dynamic.ExplicitDynamicAttribute [Fact] public void CS1971ERR_NoDynamicPhantomOnBase() { const string text = @" public class B { public virtual void M(object o) {} } public class D : B { public override void M(object o) {} void N(dynamic d) { base.M(d); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (12,9): error CS1971: The call to method 'M' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // base.M(d); Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBase, "base.M(d)").WithArguments("M")); } [Fact] public void CS1972ERR_NoDynamicPhantomOnBaseIndexer() { const string text = @" public class B { public string this[int index] { get { return ""You passed "" + index; } } } public class D : B { public void M(object o) { int[] arr = { 1, 2, 3 }; int s = base[(dynamic)o]; } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (14,17): error CS1972: The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access. // int s = base[(dynamic)o]; Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, "base[(dynamic)o]")); } [Fact] public void CS1973ERR_BadArgTypeDynamicExtension() { const string text = @" class Program { static void Main() { dynamic d = 1; B b = new B(); b.Goo(d); } } public class B { } static public class Extension { public static void Goo(this B b, int x) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (8,9): error CS1973: 'B' has no applicable method named 'Goo' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. // b.Goo(d); Diagnostic(ErrorCode.ERR_BadArgTypeDynamicExtension, "b.Goo(d)").WithArguments("B", "Goo")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_Base() { var text = @" class A { public A(int x) { } } class B : A { public B(dynamic d) : base(d) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "base")); } [Fact] public void CS1975ERR_NoDynamicPhantomOnBaseCtor_This() { var text = @" class B { public B(dynamic d) : this(d, 1) { } public B(int a, int b) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (12,9): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "this")); } [Fact] public void CS1976ERR_BadDynamicMethodArgMemgrp() { const string text = @" class Program { static void M(dynamic d) { d.Goo(M); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // d.Goo(M); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "M")); } [Fact] public void CS1977ERR_BadDynamicMethodArgLambda() { const string text = @" class Program { static void M(dynamic d) { d.Goo(()=>{}); d.Goo(delegate () {}); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (6,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // d.Goo(()=>{}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "()=>{}"), // (7,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // d.Goo(delegate () {}); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate () {}")); } [Fact, WorkItem(578352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578352")] public void CS1977ERR_BadDynamicMethodArgLambda_CreateObject() { string source = @" using System; class C { static void Main() { dynamic y = null; new C(delegate { }, y); } public C(Action a, Action y) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }); comp.VerifyDiagnostics( // (9,15): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }")); } [Fact] public void CS1660ERR_BadDynamicMethodArgLambda_CollectionInitializer() { string source = @" using System; using System.Collections; using System.Collections.Generic; unsafe class C : IEnumerable<object> { public static void M(__arglist) { int a; int* p = &a; dynamic d = null; var c = new C { { d, delegate() { } }, { d, 1, p }, { d, __arglist }, { d, GetEnumerator }, { d, SomeStaticMethod }, }; } public static void SomeStaticMethod() {} public void Add(dynamic d, int x, int* ptr) { } public void Add(dynamic d, RuntimeArgumentHandle x) { } public void Add(dynamic d, Action f) { } public void Add(dynamic d, Func<IEnumerator<object>> f) { } public IEnumerator<object> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source, new[] { CSharpRef }, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (16,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // { d, delegate() { } }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate() { }").WithLocation(16, 18), // (17,21): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. // { d, 1, p }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "p").WithArguments("int*").WithLocation(17, 21), // (18,18): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation. // { d, __arglist }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 18), // (19,13): error CS1950: The best overloaded Add method 'C.Add(dynamic, RuntimeArgumentHandle)' for the collection initializer has some invalid arguments // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgTypesForCollectionAdd, "{ d, GetEnumerator }").WithArguments("C.Add(dynamic, System.RuntimeArgumentHandle)").WithLocation(19, 13), // (19,18): error CS1503: Argument 2: cannot convert from 'method group' to 'RuntimeArgumentHandle' // { d, GetEnumerator }, Diagnostic(ErrorCode.ERR_BadArgType, "GetEnumerator").WithArguments("2", "method group", "System.RuntimeArgumentHandle").WithLocation(19, 18), // (20,18): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // { d, SomeStaticMethod }, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "SomeStaticMethod").WithLocation(20, 18)); } [Fact] public void CS1978ERR_BadDynamicMethodArg() { // The dev 10 compiler gives arguably wrong error here; it says that "TypedReference may not be // used as a type argument". Though that is true, and though what is happening here behind the scenes // is that TypedReference is being used as a type argument to a dynamic call site helper method, // that's giving an error about an implementation detail. A better error is to say that // TypedReference is not a legal type in a dynamic operation. // // Dev10 compiler didn't report an error for by-ref pointer argument. See Dev10 bug 819498. // The error should be reported for any pointer argument regardless of its refness. const string text = @" class Program { unsafe static void M(dynamic d, int* i, System.TypedReference tr) { d.Goo(i); d.Goo(tr); d.Goo(ref tr); d.Goo(out tr); d.Goo(out i); d.Goo(ref i); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,15): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (7,15): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (8,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (9,19): error CS1978: Cannot use an expression of type 'System.TypedReference' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "tr").WithArguments("System.TypedReference"), // (10,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*"), // (11,19): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "i").WithArguments("int*")); } // CS1979ERR_BadDynamicQuery --> DynamicTests.cs, DynamicQuery_* // Test CS1980ERR_DynamicAttributeMissing moved to AttributeTests_Dynamic.cs // CS1763 is covered for different code path by SymbolErrorTests.CS1763ERR_NotNullRefDefaultParameter() [WorkItem(528854, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528854")] [Fact] public void CS1763ERR_NotNullRefDefaultParameter02() { string text = @" class Program { public void Goo<T, U>(T t = default(U)) where U : T { } static void Main(string[] args) { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS1763: 't' is of type 'T'. A default parameter value of a reference type other than string can only be initialized with null // public void Goo<T, U>(T t = default(U)) where U : T Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "t").WithArguments("t", "T")); } #endregion #region "Targeted Warning Tests - please arrange tests in the order of error code" [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent() { var text = @" delegate void MyDelegate(); class MyClass { public event MyDelegate evt; // CS0067 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,29): warning CS0067: The event 'MyClass.evt' is never used // public event MyDelegate evt; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "evt").WithArguments("MyClass.evt")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessibility() { var text = @" using System; class MyClass { public event Action E1; // CS0067 internal event Action E2; // CS0067 protected internal event Action E3; // CS0067 protected event Action E4; // CS0067 private event Action E5; // CS0067 } "; CreateCompilation(text).VerifyDiagnostics( // (5,25): warning CS0067: The event 'MyClass.E1' is never used // public event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("MyClass.E1"), // (6,27): warning CS0067: The event 'MyClass.E2' is never used // internal event Action E2; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E2").WithArguments("MyClass.E2"), // (7,37): warning CS0067: The event 'MyClass.E3' is never used // protected internal event Action E3; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E3").WithArguments("MyClass.E3"), // (8,28): warning CS0067: The event 'MyClass.E4' is never used // protected event Action E4; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E4").WithArguments("MyClass.E4"), // (9,26): warning CS0067: The event 'MyClass.E5' is never used // private event Action E5; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E5").WithArguments("MyClass.E5")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_StructLayout() { var text = @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct S { event Action E1; } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Kind() { var text = @" using System; class C { event Action E1; // CS0067 event Action E2 { add { } remove { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0067: The event 'C.E1' is never used // event Action E1; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1")); } [Fact, WorkItem(542396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542396"), WorkItem(546817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546817")] public void CS0067WRN_UnreferencedEvent_Accessed() { var text = @" using System; class C { event Action None; // CS0067 event Action Read; event Action Write; event Action Add; // CS0067 void M(Action a) { M(Read); Write = a; Add += a; } } "; CreateCompilation(text).VerifyDiagnostics( // (9,18): warning CS0067: The event 'C.Add' is never used // event Action Add; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Add").WithArguments("C.Add"), // (6,18): warning CS0067: The event 'C.None' is never used // event Action None; // CS0067 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "None").WithArguments("C.None")); } [Fact, WorkItem(581002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581002")] public void CS0067WRN_UnreferencedEvent_Virtual() { var text = @"class A { public virtual event System.EventHandler B; class C : A { public override event System.EventHandler B; } static int Main() { C c = new C(); A a = c; return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,46): warning CS0067: The event 'A.B' is never used // public virtual event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.B"), // (6,51): warning CS0067: The event 'A.C.B' is never used // public override event System.EventHandler B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("A.C.B")); } [Fact, WorkItem(539630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539630")] public void CS0162WRN_UnreachableCode01() { var text = @" class MyTest { } class MyClass { const MyTest test = null; public static int Main() { goto lab1; { // The following statements cannot be reached: int i = 9; // CS0162 i++; } lab1: if (test == null) { return 0; } else { return 1; // CS0162 } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "int"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(530037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530037")] public void CS0162WRN_UnreachableCode02() { var text = @" using System; public class Test { public static void Main(string[] args) { // (1) do { for (; ; ) { } } while (args.Length > 0); // Native CS0162 // (2) for (; ; ) // Roslyn CS0162 { goto L2; Console.WriteLine(""Unreachable code""); L2: // Roslyn CS0162 break; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,5): warning CS0162: Unreachable code detected // for (; ; ) // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "for"), // (18,5): warning CS0162: Unreachable code detected // L2: // Roslyn CS0162 Diagnostic(ErrorCode.WRN_UnreachableCode, "L2") ); } [Fact, WorkItem(539873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539873"), WorkItem(539981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539981")] public void CS0162WRN_UnreachableCode04() { var text = @" public class Cls { public static int Main() { goto Label2; return 0; Label1: return 1; Label2: goto Label1; return 2; } delegate void Sub_0(); static void M() { Sub_0 s1_3 = () => { if (2 == 1) return; else return; }; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return"), Diagnostic(ErrorCode.WRN_UnreachableCode, "return")); } [Fact, WorkItem(540901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540901")] public void CS0162WRN_UnreachableCode06_Loops() { var text = @" class Program { void F() { } void T() { for (int i = 0; i < 0; F(), i++) // F() is unreachable { return; } } static void Main() { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { goto stop; System.Console.WriteLine(y); // unreachable } foreach (char y in x) { throw new System.Exception(); System.Console.WriteLine(y); // unreachable } stop: return; } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreachableCode, "F"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System"), Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode06_Foreach03() { var text = @" public class Test { static public void Main(string[] args) { string[] S = new string[] { ""ABC"", ""XYZ"" }; foreach (string x in S) { foreach (char y in x) { return; System.Console.WriteLine(y); } } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "System")); } [Fact] public void CS0162WRN_UnreachableCode07_GotoInLambda() { var text = @" using System; class Program { static void Main() { Action a = () => { goto label1; Console.WriteLine(""unreachable""); label1: Console.WriteLine(""reachable""); }; } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, @"Console")); } [Fact] public void CS0164WRN_UnreferencedLabel() { var text = @" public class a { public int i = 0; public static void Main() { int i = 0; // CS0164 l1: i++; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(9, 7)); } [Fact] public void CS0168WRN_UnreferencedVar01() { var text = @" public class clx { public int i; } public class clz { public static void Main() { int j ; // CS0168, uncomment the following line // j++; clx a; // CS0168, try the following line instead // clx a = new clx(); } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(11, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(13, 13)); } [Fact] public void CS0168WRN_UnreferencedVar02() { var text = @"using System; class C { static void M() { try { } catch (InvalidOperationException e) { } catch (InvalidCastException e) { throw; } catch (Exception e) { throw e; } } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(7, 42), Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(8, 37)); } [Fact] public void CS0169WRN_UnreferencedField() { var text = @" public class ClassX { int i; // CS0169, i is not used anywhere public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,8): warning CS0169: The field 'ClassX.i' is never used // int i; // CS0169, i is not used anywhere Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("ClassX.i") ); } [Fact] public void CS0169WRN_UnreferencedField02() { var text = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""OtherAssembly"")] internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (8,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (14,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0169WRN_UnreferencedField03() { var text = @"internal class InternalClass { internal int ActuallyInternal; internal int ActuallyInternalAssigned = 0; private int ActuallyPrivate; private int ActuallyPrivateAssigned = 0; public int EffectivelyInternal; public int EffectivelyInternalAssigned = 0; private class PrivateClass { public int EffectivelyPrivate; public int EffectivelyPrivateAssigned = 0; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,18): warning CS0649: Field 'InternalClass.ActuallyInternal' is never assigned to, and will always have its default value 0 // internal int ActuallyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ActuallyInternal").WithArguments("InternalClass.ActuallyInternal", "0"), // (5,17): warning CS0169: The field 'InternalClass.ActuallyPrivate' is never used // private int ActuallyPrivate; Diagnostic(ErrorCode.WRN_UnreferencedField, "ActuallyPrivate").WithArguments("InternalClass.ActuallyPrivate"), // (6,17): warning CS0414: The field 'InternalClass.ActuallyPrivateAssigned' is assigned but its value is never used // private int ActuallyPrivateAssigned = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "ActuallyPrivateAssigned").WithArguments("InternalClass.ActuallyPrivateAssigned"), // (7,16): warning CS0649: Field 'InternalClass.EffectivelyInternal' is never assigned to, and will always have its default value 0 // public int EffectivelyInternal; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyInternal").WithArguments("InternalClass.EffectivelyInternal", "0"), // (12,20): warning CS0649: Field 'InternalClass.PrivateClass.EffectivelyPrivate' is never assigned to, and will always have its default value 0 // public int EffectivelyPrivate; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "EffectivelyPrivate").WithArguments("InternalClass.PrivateClass.EffectivelyPrivate", "0") ); } [Fact] public void CS0183WRN_IsAlwaysTrue() { var text = @"using System; public class IsTest10 { public static int Main(String[] args) { Object obj3 = null; String str2 = ""Is 'is' too strict, per error CS0183?""; obj3 = str2; if (str2 is Object) // no error CS0183 Console.WriteLine(""str2 is Object""); Int32 int2 = 1; if (int2 is Object) // error CS0183 Console.WriteLine(""int2 is Object""); return 0; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_IsAlwaysTrue, Line = 14, Column = 13, IsWarning = true }); // TODO: extra checking } // Note: CS0184 tests moved to CodeGenOperator.cs to include IL verification. [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField() { var text = @" class X : System.MarshalByRefObject { public int i; } class M { public int i; static void AddSeventeen(ref int i) { i += 17; } static void Main() { X x = new X(); x.i = 12; AddSeventeen(ref x.i); // CS0197 // OK M m = new M(); m.i = 12; AddSeventeen(ref m.i); } } "; CreateCompilation(text).VerifyDiagnostics( // (19,24): warning CS0197: Passing 'X.i' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // AddSeventeen(ref x.i); // CS0197 Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "x.i").WithArguments("X.i")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_RefKind() { var text = @" class NotByRef { public int Instance; public static int Static; } class ByRef : System.MarshalByRefObject { public int Instance; public static int Static; } class Test { void M(ByRef b, NotByRef n) { None(n.Instance); Out(out n.Instance); Ref(ref n.Instance); None(NotByRef.Static); Out(out NotByRef.Static); Ref(ref NotByRef.Static); None(b.Instance); Out(out b.Instance); Ref(ref b.Instance); None(ByRef.Static); Out(out ByRef.Static); Ref(ref ByRef.Static); } void None(int x) { throw null; } void Out(out int x) { throw null; } void Ref(ref int x) { throw null; } } "; CreateCompilation(text).VerifyDiagnostics( // (27,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Out(out b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance"), // (28,17): warning CS0197: Passing 'ByRef.Instance' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref b.Instance); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "b.Instance").WithArguments("ByRef.Instance")); } [WorkItem(530361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530361")] [Fact] public void CS0197WRN_ByRefNonAgileField_Receiver() { var text = @" using System; class ByRef : MarshalByRefObject { public int F; protected void Ref(ref int x) { } void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); } } class Derived : ByRef { void Test() { Ref(ref F); Ref(ref this.F); Ref(ref ((ByRef)this).F); Ref(ref base.F); //Ref(ref ((ByRef)base).F); } } "; CreateCompilation(text).VerifyDiagnostics( // (15,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F"), // (26,17): warning CS0197: Passing 'ByRef.F' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class // Ref(ref ((ByRef)this).F); Diagnostic(ErrorCode.WRN_ByRefNonAgileField, "((ByRef)this).F").WithArguments("ByRef.F")); } [Fact] public void CS0219WRN_UnreferencedVarAssg01() { var text = @"public class MyClass { public static void Main() { int a = 0; // CS0219 } }"; CreateCompilation(text).VerifyDiagnostics( // (5,13): warning CS0219: The variable 'a' is assigned but its value is never used // int a = 0; // CS0219 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a") ); } [Fact] public void CS0219WRN_UnreferencedVarAssg02() { var text = @" public class clx { static void Main(string[] args) { int x = 1; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13)); } [Fact] public void CS0219WRN_UnreferencedVarAssg03() { var text = @" public class clx { static void Main(string[] args) { int? x; x = null; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 14)); } [Fact, WorkItem(542473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542473"), WorkItem(542474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542474")] public void CS0219WRN_UnreferencedVarAssg_StructString() { var text = @" class program { static void Main(string[] args) { s1 y = new s1(); string s = """"; } } struct s1 { } "; CreateCompilation(text).VerifyDiagnostics( // (6,12): warning CS0219: The variable 'y' is assigned but its value is never used // s1 y = new s1(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(6, 12), Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(7, 16) ); } [Fact, WorkItem(542494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542494")] public void CS0219WRN_UnreferencedVarAssg_Default() { var text = @" class S { public int x = 5; } class C { public static void Main() { var x = default(S); } }"; CreateCompilation(text).VerifyDiagnostics( // (11,13): warning CS0219: The variable 'x' is assigned but its value is never used // var x = default(S); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(11, 13) ); } [Fact] public void CS0219WRN_UnreferencedVarAssg_For() { var text = @" class C { public static void Main() { for (int i = 1; ; ) { break; } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,18): warning CS0219: The variable 'i' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 18) ); } [Fact, WorkItem(546619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546619")] public void NoCS0219WRN_UnreferencedVarAssg_ObjectInitializer() { var text = @" struct S { public int X { set {} } } class C { public static void Main() { S s = new S { X = 2 }; // no error - not a constant int? i = new int? { }; // ditto - not the default value (though bitwise equal to it) } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(542472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542472")] public void CS0251WRN_NegativeArrayIndex() { var text = @" class C { static void Main() { int[] a = new int[1]; int[,] b = new int[1, 1]; a[-1] = 1; // CS0251 a[-1, -1] = 1; // Dev10 reports CS0022 and CS0251 (twice), Roslyn reports CS0022 b[-1] = 1; // CS0022 b[-1, -1] = 1; // fine } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0251: Indexing an array with a negative index (array indices always start at zero) Diagnostic(ErrorCode.WRN_NegativeArrayIndex, "-1"), // (9,9): error CS0022: Wrong number of indices inside []; expected '1' Diagnostic(ErrorCode.ERR_BadIndexCount, "a[-1, -1]").WithArguments("1"), // (10,9): error CS0022: Wrong number of indices inside []; expected '2' Diagnostic(ErrorCode.ERR_BadIndexCount, "b[-1]").WithArguments("2")); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0252WRN_BadRefCompareLeft() { var text = @"class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool b = o == s; // CS0252 } }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string' // bool b = o == s; // CS0252 Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "o == s").WithArguments("string") ); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_02() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { MethodSymbol a1 = null; MethodSymbol a2 = new MethodSymbol(); // In these cases the programmer explicitly inserted a cast to use object equality instead // of the user-defined equality operator. Since the programmer did this explicitly, in // Roslyn we suppress the diagnostic that was given by the native compiler suggesting casting // the object-typed operand back to type Symbol to get value equality. Console.WriteLine((object)a1 == a2); Console.WriteLine((object)a1 != a2); Console.WriteLine((object)a2 == a1); Console.WriteLine((object)a2 != a1); Console.WriteLine(a1 == (object)a2); Console.WriteLine(a1 != (object)a2); Console.WriteLine(a2 == (object)a1); Console.WriteLine(a2 != (object)a1); } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(781070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781070")] [Fact] public void CS0252WRN_BadRefCompareLeft_03() { var text = @"using System; public class Symbol { public static bool operator ==(Symbol a, Symbol b) { return ReferenceEquals(a, null) || ReferenceEquals(b, null) || ReferenceEquals(a, b); } public static bool operator !=(Symbol a, Symbol b) { return !(a == b); } public override bool Equals(object obj) { return (obj is Symbol || obj == null) ? this == (Symbol)obj : false; } public override int GetHashCode() { return 0; } } public class MethodSymbol : Symbol { } class Program { static void Main(string[] args) { Object a1 = null; MethodSymbol a2 = new MethodSymbol(); Console.WriteLine(a1 == a2); Console.WriteLine(a1 != a2); Console.WriteLine(a2 == a1); Console.WriteLine(a2 != a1); } }"; CreateCompilation(text).VerifyDiagnostics( // (34,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 == a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 == a2").WithArguments("Symbol"), // (35,27): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'Symbol' // Console.WriteLine(a1 != a2); Diagnostic(ErrorCode.WRN_BadRefCompareLeft, "a1 != a2").WithArguments("Symbol"), // (36,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 == a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 == a1").WithArguments("Symbol"), // (37,27): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'Symbol' // Console.WriteLine(a2 != a1); Diagnostic(ErrorCode.WRN_BadRefCompareRight, "a2 != a1").WithArguments("Symbol") ); } [WorkItem(530362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530362"), WorkItem(670322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670322")] [Fact] public void CS0253WRN_BadRefCompareRight() { var text = @" class MyClass { public static void Main() { string s = ""11""; object o = s + s; bool c = s == o; // CS0253 // try the following line instead // bool c = s == (string)o; } }"; CreateCompilation(text).VerifyDiagnostics( // (9,16): warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string' // bool c = s == o; // CS0253 Diagnostic(ErrorCode.WRN_BadRefCompareRight, "s == o").WithArguments("string") ); } [WorkItem(730177, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730177")] [Fact] public void CS0253WRN_BadRefCompare_None() { var text = @"using System; class MyClass { public static void Main() { MulticastDelegate x1 = null; bool b1 = x1 == null; bool b2 = x1 != null; bool b3 = null == x1; bool b4 = null != x1; } }"; CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(542399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542399")] [Fact] public void CS0278WRN_PatternIsAmbiguous01() { var text = @" using System.Collections.Generic; public class myTest { public static void TestForeach<W>(W w) where W: IEnumerable<int>, IEnumerable<string> { foreach (int i in w) {} // CS0278 } } "; CreateCompilation(text).VerifyDiagnostics( // (8,25): warning CS0278: 'W' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()'. // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "w").WithArguments("W", "collection", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()"), // (8,25): error CS1640: foreach statement cannot operate on variables of type 'W' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation // foreach (int i in w) {} // CS0278 Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "w").WithArguments("W", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void CS0278WRN_PatternIsAmbiguous02() { var text = @"using System.Collections; using System.Collections.Generic; class A : IEnumerable<A> { public IEnumerator<A> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : IEnumerable<B> { IEnumerator<B> IEnumerable<B>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C : IEnumerable<C>, IEnumerable<string> { public IEnumerator<C> GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class D : IEnumerable<D>, IEnumerable<string> { IEnumerator<D> IEnumerable<D>.GetEnumerator() { return null; } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class E { static void M<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) where T1 : A, IEnumerable<A> // duplicate interfaces where T2 : B, IEnumerable<B> // duplicate interfaces where T3 : A, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T4 : B, IEnumerable<string>, IEnumerable<int> // multiple interfaces where T5 : C, IEnumerable<int> // multiple interfaces where T6 : D, IEnumerable<int> // multiple interfaces where T7 : A, IEnumerable<string>, IEnumerable<A> // duplicate and multiple interfaces where T8 : B, IEnumerable<string>, IEnumerable<B> // duplicate and multiple interfaces where T9 : C, IEnumerable<C> // duplicate and multiple interfaces where T10 : D, IEnumerable<D> // duplicate and multiple interfaces { foreach (A o in t1) { } foreach (B o in t2) { } foreach (A o in t3) { } foreach (var o in t4) { } foreach (C o in t5) { } foreach (int o in t6) { } foreach (A o in t7) { } foreach (var o in t8) { } foreach (C o in t9) { } foreach (D o in t10) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (42,27): warning CS0278: 'T4' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<int>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t4").WithArguments("T4", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<int>.GetEnumerator()").WithLocation(42, 27), // (42,27): error CS1640: foreach statement cannot operate on variables of type 'T4' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t4").WithArguments("T4", "System.Collections.Generic.IEnumerable<T>").WithLocation(42, 27), // (46,27): warning CS0278: 'T8' does not implement the 'collection' pattern. 'System.Collections.Generic.IEnumerable<string>.GetEnumerator()' is ambiguous with 'System.Collections.Generic.IEnumerable<B>.GetEnumerator()'. Diagnostic(ErrorCode.WRN_PatternIsAmbiguous, "t8").WithArguments("T8", "collection", "System.Collections.Generic.IEnumerable<string>.GetEnumerator()", "System.Collections.Generic.IEnumerable<B>.GetEnumerator()").WithLocation(46, 27), // (46,27): error CS1640: foreach statement cannot operate on variables of type 'T8' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t8").WithArguments("T8", "System.Collections.Generic.IEnumerable<T>").WithLocation(46, 27)); } [Fact] public void CS0279WRN_PatternStaticOrInaccessible() { var text = @" using System.Collections; public class myTest : IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } public static void Main() { foreach (int i in new myTest()) {} // CS0279 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,27): warning CS0279: 'myTest' does not implement the 'collection' pattern. 'myTest.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new myTest()").WithArguments("myTest", "collection", "myTest.GetEnumerator()")); } [Fact] public void CS0280WRN_PatternBadSignature() { var text = @" using System.Collections; public class ValidBase: IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return null; } internal IEnumerator GetEnumerator() { return null; } } class Derived : ValidBase { // field, not method new public int GetEnumerator; } public class Test { public static void Main() { foreach (int i in new Derived()) {} // CS0280 } } "; CreateCompilation(text).VerifyDiagnostics( // (27,25): warning CS0280: 'Derived' does not implement the 'collection' pattern. 'Derived.GetEnumerator' has the wrong signature. // foreach (int i in new Derived()) {} // CS0280 Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Derived()").WithArguments("Derived", "collection", "Derived.GetEnumerator"), // (20,19): warning CS0649: Field 'Derived.GetEnumerator' is never assigned to, and will always have its default value 0 // new public int GetEnumerator; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "GetEnumerator").WithArguments("Derived.GetEnumerator", "0") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg() { var text = @" class C { private int i = 1; // CS0414 public static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,16): warning CS0414: The field 'C.i' is assigned but its value is never used // private int i = 1; // CS0414 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("C.i") ); } [Fact] public void CS0414WRN_UnreferencedFieldAssg02() { var text = @"class S<T1, T2> { T1 t1_field = default(T1); }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,8): warning CS0414: The field 'S<T1, T2>.t1_field' is assigned but its value is never used // T1 t1_field = default(T1); Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "t1_field").WithArguments("S<T1, T2>.t1_field").WithLocation(3, 8) ); } [Fact] public void CS0419WRN_AmbiguousXMLReference() { var text = @" interface I { void F(); void F(int i); } public class MyClass { /// <see cref=""I.F""/> public static void MyMethod(int i) { } public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,14): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass' // public class MyClass Diagnostic(ErrorCode.WRN_MissingXMLComment, "MyClass").WithArguments("MyClass"), // (9,19): warning CS0419: Ambiguous reference in cref attribute: 'I.F'. Assuming 'I.F()', but could have also matched other overloads including 'I.F(int)'. // /// <see cref="I.F"/> Diagnostic(ErrorCode.WRN_AmbiguousXMLReference, "I.F").WithArguments("I.F", "I.F()", "I.F(int)"), // (13,23): warning CS1591: Missing XML comment for publicly visible type or member 'MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("MyClass.Main()")); } [Fact] public void CS0420WRN_VolatileByRef() { var text = @" class TestClass { private volatile int i; public void TestVolatileRef(ref int ii) { } public void TestVolatileOut(out int ii) { ii = 0; } public static void Main() { TestClass x = new TestClass(); x.TestVolatileRef(ref x.i); // CS0420 x.TestVolatileOut(out x.i); // CS0420 } } "; CreateCompilation(text).VerifyDiagnostics( // (18,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i"), // (19,29): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x.i").WithArguments("TestClass.i")); } [Fact] public void CS0420WRN_VolatileByRef_Suppressed() { var text = @" using System.Threading; class TestClass { private static volatile int x = 0; public static void TestVolatileByRef() { Interlocked.Increment(ref x); // no CS0420 Interlocked.Decrement(ref x); // no CS0420 Interlocked.Add(ref x, 0); // no CS0420 Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 Interlocked.Exchange(ref x, 0); // no CS0420 // using fully qualified name System.Threading.Interlocked.Increment(ref x); // no CS0420 System.Threading.Interlocked.Decrement(ref x); // no CS0420 System.Threading.Interlocked.Add(ref x, 0); // no CS0420 System.Threading.Interlocked.CompareExchange(ref x, 0, 0); // no CS0420 System.Threading.Interlocked.Exchange(ref x, 0); // no CS0420 // passing volatile variables in a nested way Interlocked.Increment(ref Method1(ref x).y); // CS0420 for x Interlocked.Decrement(ref Method1(ref x).y); // CS0420 for x Interlocked.Add(ref Method1(ref x).y, 0); // CS0420 for x Interlocked.CompareExchange(ref Method1(ref x).y, 0, 0); // CS0420 for x Interlocked.Exchange(ref Method1(ref x).y, 0); // CS0420 for x // located as a function argument goo(Interlocked.Increment(ref x)); // no CS0420 } public static int goo(int x) { return x; } public static MyClass Method1(ref int x) { return new MyClass(); } public class MyClass { public volatile int y = 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (24,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (25,45): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (26,39): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (27,51): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x"), // (28,44): warning CS0420: 'TestClass.i': a reference to a volatile field will not be treated as volatile Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("TestClass.x")); } [WorkItem(728380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728380")] [Fact] public void Repro728380() { var source = @" class Test { static volatile int x; unsafe static void goo(int* pX) { } static int Main() { unsafe { Test.goo(&x); } return 1; } } "; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,27): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.ERR_FixedNeeded, "&x"), // (9,28): warning CS0420: 'Test.x': a reference to a volatile field will not be treated as volatile // unsafe { Test.goo(&x); } Diagnostic(ErrorCode.WRN_VolatileByRef, "x").WithArguments("Test.x")); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275")] public void CS0429WRN_UnreachableExpr() { var text = @" public class cs0429 { public static void Main() { if (false && myTest()) // CS0429 // Try the following line instead: // if (true && myTest()) { } else { int i = 0; i++; } } static bool myTest() { return true; } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(528275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528275"), WorkItem(530071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530071")] public void CS0429WRN_UnreachableExpr_02() { var text = @" class Program { static bool b = true; const bool con = true; static void Main(string[] args) { int x = 1; int y = 1; int s = true ? x++ : y++; // y++ unreachable s = x == y ? x++ : y++; // OK s = con ? x++ : y++; // y++ unreachable bool con1 = true; s = con1 ? x++ : y++; // OK s = b ? x++ : y++; s = 1 < 2 ? x++ : y++; // y++ unreachable } } "; // Dev11 compiler reports WRN_UnreachableExpr, but reachability is defined for statements not for expressions. // We don't report the warning. CreateCompilation(text).VerifyDiagnostics(); } [Fact, WorkItem(543943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543943")] public void CS0458WRN_AlwaysNull() { var text = @" public class Test { public static void Main() { int? x = 0; x = null + x; x = x + default(int?); x += new int?(); x = null - x; x = x - default(int?); x -= new int?(); x = null * x; x = x * default(int?); x *= new int?(); x = null / x; x = x / default(int?); x /= new int?(); x = null % x; x = x % default(int?); x %= new int?(); x = null << x; x = x << default(int?); x <<= new int?(); x = null >> x; x = x >> default(int?); x >>= new int?(); x = null & x; x = x & default(int?); x &= new int?(); x = null | x; x = x | default(int?); x |= new int?(); x = null ^ x; x = x ^ default(int?); x ^= new int?(); //The below block of code should not raise a warning bool? y = null; y = y & null; y = y |false; y = true | null; double? d = +default(double?); int? i = -default(int?); long? l = ~default(long?); bool? b = !default(bool?); } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AlwaysNull, "null + x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x + default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x += new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null - x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x - default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x -= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null * x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x * default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x *= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null / x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x / default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x /= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null % x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x % default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x %= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null << x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x << default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x <<= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null >> x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >> default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x >>= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null & x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x & default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x &= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null | x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x | default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x |= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "null ^ x").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^ default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "x ^= new int?()").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "+default(double?)").WithArguments("double?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "-default(int?)").WithArguments("int?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "~default(long?)").WithArguments("long?"), Diagnostic(ErrorCode.WRN_AlwaysNull, "!default(bool?)").WithArguments("bool?") ); } [Fact] public void CS0464WRN_CmpAlwaysFalse() { var text = @" class MyClass { public struct S { public static bool operator <(S x, S y) { return true; } public static bool operator >(S x, S y) { return true; } public static bool operator <=(S x, S y) { return true; } public static bool operator >=(S x, S y) { return true; } } public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } public static void Main() { S s = default(S); S? t = s; int i = 0; int? n = i; W(i < null); // CS0464 W(i <= null); // CS0464 W(i > null); // CS0464 W(i >= null); // CS0464 W(n < null); // CS0464 W(n <= null); // CS0464 W(n > null); // CS0464 W(n >= null); // CS0464 W(s < null); // CS0464 W(s <= null); // CS0464 W(s > null); // CS0464 W(s >= null); // CS0464 W(t < null); // CS0464 W(t <= null); // CS0464 W(t > null); // CS0464 W(t >= null); // CS0464 W(i < default(short?)); // CS0464 W(i <= default(short?)); // CS0464 W(i > default(short?)); // CS0464 W(i >= default(short?)); // CS0464 W(n < default(short?)); // CS0464 W(n <= default(short?)); // CS0464 W(n > default(short?)); // CS0464 W(n >= default(short?)); // CS0464 W(s < default(S?)); // CS0464 W(s <= default(S?)); // CS0464 W(s > default(S?)); // CS0464 W(s >= default(S?)); // CS0464 W(t < default(S?)); // CS0464 W(t <= default(S?)); // CS0464 W(t > default(S?)); // CS0464 W(t >= default(S?)); // CS0464 W(i < new sbyte?()); // CS0464 W(i <= new sbyte?()); // CS0464 W(i > new sbyte?()); // CS0464 W(i >= new sbyte?()); // CS0464 W(n < new sbyte?()); // CS0464 W(n <= new sbyte?()); // CS0464 W(n > new sbyte?()); // CS0464 W(n >= new sbyte?()); // CS0464 W(s < new S?()); // CS0464 W(s <= new S?()); // CS0464 W(s > new S?()); // CS0464 W(s >= new S?()); // CS0464 W(t < new S?()); // CS0464 W(t <= new S?()); // CS0464 W(t > new S?()); // CS0464 W(t >= new S?()); // CS0464 System.Console.WriteLine(); W(null < i); // CS0464 W(null <= i); // CS0464 W(null > i); // CS0464 W(null >= i); // CS0464 W(null < n); // CS0464 W(null <= n); // CS0464 W(null > n); // CS0464 W(null >= n); // CS0464 W(null < s); // CS0464 W(null <= s); // CS0464 W(null > s); // CS0464 W(null >= s); // CS0464 W(null < t); // CS0464 W(null <= t); // CS0464 W(null > t); // CS0464 W(null >= t); // CS0464 W(default(short?) < i); // CS0464 W(default(short?) <= i); // CS0464 W(default(short?) > i); // CS0464 W(default(short?) >= i); // CS0464 W(default(short?) < n); // CS0464 W(default(short?) <= n); // CS0464 W(default(short?) > n); // CS0464 W(default(short?) >= n); // CS0464 W(default(S?) < s); // CS0464 W(default(S?) <= s); // CS0464 W(default(S?) > s); // CS0464 W(default(S?) >= s); // CS0464 W(default(S?) < t); // CS0464 W(default(S?) <= t); // CS0464 W(default(S?) > t); // CS0464 W(default(S?) >= t); // CS0464 W(new sbyte?() < i); // CS0464 W(new sbyte?() <= i); // CS0464 W(new sbyte?() > i); // CS0464 W(new sbyte?() >= i); // CS0464 W(new sbyte?() < n); // CS0464 W(new sbyte?() <= n); // CS0464 W(new sbyte?() > n); // CS0464 W(new sbyte?() > n); // CS0464 W(new S?() < s); // CS0464 W(new S?() <= s); // CS0464 W(new S?() > s); // CS0464 W(new S?() >= s); // CS0464 W(new S?() < t); // CS0464 W(new S?() <= t); // CS0464 W(new S?() > t); // CS0464 W(new S?() > t); // CS0464 System.Console.WriteLine(); W(null > null); // CS0464 W(null >= null); // CS0464 W(null < null); // CS0464 W(null <= null); // CS0464 } } "; var verifier = CompileAndVerify(source: text, expectedOutput: @"ffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffff ffff"); CreateCompilation(text).VerifyDiagnostics( // (25,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < null").WithArguments("int?"), // (26,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= null").WithArguments("int?"), // (27,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > null").WithArguments("int?"), // (28,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(i >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= null").WithArguments("int?"), // (30,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < null").WithArguments("int?"), // (31,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= null").WithArguments("int?"), // (32,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > null").WithArguments("int?"), // (33,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(n >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= null").WithArguments("int?"), // (35,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < null").WithArguments("MyClass.S?"), // (36,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= null").WithArguments("MyClass.S?"), // (37,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > null").WithArguments("MyClass.S?"), // (38,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= null").WithArguments("MyClass.S?"), // (40,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < null").WithArguments("MyClass.S?"), // (41,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= null").WithArguments("MyClass.S?"), // (42,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > null").WithArguments("MyClass.S?"), // (43,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= null").WithArguments("MyClass.S?"), // (45,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < default(short?)").WithArguments("short?"), // (46,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= default(short?)").WithArguments("short?"), // (47,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > default(short?)").WithArguments("short?"), // (48,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(i >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= default(short?)").WithArguments("short?"), // (50,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n < default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < default(short?)").WithArguments("short?"), // (51,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n <= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= default(short?)").WithArguments("short?"), // (52,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n > default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > default(short?)").WithArguments("short?"), // (53,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(n >= default(short?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= default(short?)").WithArguments("short?"), // (55,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < default(S?)").WithArguments("MyClass.S?"), // (56,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= default(S?)").WithArguments("MyClass.S?"), // (57,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > default(S?)").WithArguments("MyClass.S?"), // (58,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= default(S?)").WithArguments("MyClass.S?"), // (60,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < default(S?)").WithArguments("MyClass.S?"), // (61,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= default(S?)").WithArguments("MyClass.S?"), // (62,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > default(S?)").WithArguments("MyClass.S?"), // (63,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= default(S?)); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= default(S?)").WithArguments("MyClass.S?"), // (65,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i < new sbyte?()").WithArguments("sbyte?"), // (66,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i <= new sbyte?()").WithArguments("sbyte?"), // (67,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i > new sbyte?()").WithArguments("sbyte?"), // (68,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(i >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "i >= new sbyte?()").WithArguments("sbyte?"), // (70,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n < new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n < new sbyte?()").WithArguments("sbyte?"), // (71,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n <= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n <= new sbyte?()").WithArguments("sbyte?"), // (72,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n > new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n > new sbyte?()").WithArguments("sbyte?"), // (73,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(n >= new sbyte?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "n >= new sbyte?()").WithArguments("sbyte?"), // (75,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s < new S?()").WithArguments("MyClass.S?"), // (76,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s <= new S?()").WithArguments("MyClass.S?"), // (77,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s > new S?()").WithArguments("MyClass.S?"), // (78,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(s >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "s >= new S?()").WithArguments("MyClass.S?"), // (80,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t < new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t < new S?()").WithArguments("MyClass.S?"), // (81,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t <= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t <= new S?()").WithArguments("MyClass.S?"), // (82,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t > new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t > new S?()").WithArguments("MyClass.S?"), // (83,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(t >= new S?()); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "t >= new S?()").WithArguments("MyClass.S?"), // (87,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < i").WithArguments("int?"), // (88,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= i").WithArguments("int?"), // (89,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > i").WithArguments("int?"), // (90,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= i").WithArguments("int?"), // (92,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < n").WithArguments("int?"), // (93,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= n").WithArguments("int?"), // (94,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > n").WithArguments("int?"), // (95,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= n").WithArguments("int?"), // (97,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < s").WithArguments("MyClass.S?"), // (98,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= s").WithArguments("MyClass.S?"), // (99,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > s").WithArguments("MyClass.S?"), // (100,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= s").WithArguments("MyClass.S?"), // (102,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < t").WithArguments("MyClass.S?"), // (103,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= t").WithArguments("MyClass.S?"), // (104,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > t").WithArguments("MyClass.S?"), // (105,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(null >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= t").WithArguments("MyClass.S?"), // (107,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < i").WithArguments("short?"), // (108,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= i").WithArguments("short?"), // (109,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > i").WithArguments("short?"), // (110,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= i").WithArguments("short?"), // (112,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) < n").WithArguments("short?"), // (113,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) <= n").WithArguments("short?"), // (114,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) > n").WithArguments("short?"), // (115,11): warning CS0464: Comparing with null of type 'short?' always produces 'false' // W(default(short?) >= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(short?) >= n").WithArguments("short?"), // (117,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < s").WithArguments("MyClass.S?"), // (118,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= s").WithArguments("MyClass.S?"), // (119,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > s").WithArguments("MyClass.S?"), // (120,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= s").WithArguments("MyClass.S?"), // (122,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) < t").WithArguments("MyClass.S?"), // (123,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) <= t").WithArguments("MyClass.S?"), // (124,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) > t").WithArguments("MyClass.S?"), // (125,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(default(S?) >= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "default(S?) >= t").WithArguments("MyClass.S?"), // (127,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < i").WithArguments("sbyte?"), // (128,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= i").WithArguments("sbyte?"), // (129,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > i").WithArguments("sbyte?"), // (130,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() >= i); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() >= i").WithArguments("sbyte?"), // (132,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() < n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() < n").WithArguments("sbyte?"), // (133,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() <= n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() <= n").WithArguments("sbyte?"), // (134,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (135,11): warning CS0464: Comparing with null of type 'sbyte?' always produces 'false' // W(new sbyte?() > n); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new sbyte?() > n").WithArguments("sbyte?"), // (137,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < s").WithArguments("MyClass.S?"), // (138,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= s").WithArguments("MyClass.S?"), // (139,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > s").WithArguments("MyClass.S?"), // (140,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() >= s); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() >= s").WithArguments("MyClass.S?"), // (142,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() < t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() < t").WithArguments("MyClass.S?"), // (143,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() <= t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() <= t").WithArguments("MyClass.S?"), // (144,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (145,11): warning CS0464: Comparing with null of type 'MyClass.S?' always produces 'false' // W(new S?() > t); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "new S?() > t").WithArguments("MyClass.S?"), // (149,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null > null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null > null").WithArguments("int?"), // (150,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null >= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null >= null").WithArguments("int?"), // (151,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null < null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null < null").WithArguments("int?"), // (152,11): warning CS0464: Comparing with null of type 'int?' always produces 'false' // W(null <= null); // CS0464 Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "null <= null").WithArguments("int?") ); } [Fact] public void CS0469WRN_GotoCaseShouldConvert() { var text = @" class Test { static void Main() { char c = (char)180; switch (c) { case (char)127: break; case (char)180: goto case 127; // CS0469 // try the following line instead // goto case (char) 127; } } } "; CreateCompilation(text).VerifyDiagnostics( // (13,13): warning CS0469: The 'goto case' value is not implicitly convertible to type 'char' // goto case 127; // CS0469 Diagnostic(ErrorCode.WRN_GotoCaseShouldConvert, "goto case 127;").WithArguments("char").WithLocation(13, 13) ); } [Fact, WorkItem(663, "https://github.com/dotnet/roslyn/issues/663")] public void CS0472WRN_NubExprIsConstBool() { // Due to a long-standing bug, the native compiler does not produce warnings for "guid == null", // but does for "int == null". Roslyn corrects this lapse and produces warnings for both built-in // and user-defined lifted equality operators, but the new warnings for user-defined types are // only given with /warn:n where n >= 5. var text = @" using System; class MyClass { public static void W(bool b) { System.Console.Write(b ? 't' : 'f'); } enum E : int { }; public static void Main() { Guid g = default(Guid); Guid? h = g; int i = 0; int? n = i; W(i == null); // CS0472 W(i != null); // CS0472 W(n == null); // no error W(n != null); // no error W(g == null); // CS0472 W(g != null); // CS0472 W(h == null); // no error W(h != null); // no error W(i == default(short?)); // CS0472 W(i != default(short?)); // CS0472 W(n == default(short?)); // no error W(n != default(short?)); // no error W(g == default(Guid?)); // CS0472 W(g != default(Guid?)); // CS0472 W(h == default(Guid?)); // no error W(h != default(Guid?)); // no error W(i == new sbyte?()); // CS0472 W(i != new sbyte?()); // CS0472 W(n == new sbyte?()); // no error W(n != new sbyte?()); // no error W(g == new Guid?()); // CS0472 W(g != new Guid?()); // CS0472 W(h == new Guid?()); // no error W(h != new Guid?()); // no error System.Console.WriteLine(); W(null == i); // CS0472 W(null != i); // CS0472 W(null == n); // no error W(null != n); // no error W(null == g); // CS0472 W(null != g); // CS0472 W(null == h); // no error W(null != h); // no error W(default(long?) == i); // CS0472 W(default(long?) != i); // CS0472 W(default(long?) == n); // no error W(default(long?) != n); // no error W(default(Guid?) == g); // CS0472 W(default(Guid?) != g); // CS0472 W(default(Guid?) == h); // no error W(default(Guid?) != h); // no error W(new double?() == i); // CS0472 W(new double?() != i); // CS0472 W(new double?() == n); // no error W(new double?() != n); // no error W(new Guid?() == g); // CS0472 W(new Guid?() != g); // CS0472 W(new Guid?() == h); // no error W(new Guid?() != h); // no error System.Console.WriteLine(); W(null == null); // No error, because both sides are nullable, but of course W(null != null); // we could give a warning here as well. System.Console.WriteLine(); //check comparisons with converted constants W((E?)1 == null); W(null != (E?)1); W((int?)1 == null); W(null != (int?)1); //check comparisons when null is converted W(0 == (int?)null); W((int?)null != 0); W(0 == (E?)null); W((E?)null != 0); } } "; string expected = @"ftftftftftftftftftftftft ftftftftftftftftftftftft tf ftftftft"; var fullExpected = new DiagnosticDescription[] { // (19,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(19, 11), // (20,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(i != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != null").WithArguments("true", "int", "int?").WithLocation(20, 11), // (23,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == null").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(23, 11), // (24,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != null); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != null").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(24, 11), // (28,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i == default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == default(short?)").WithArguments("false", "int", "short?").WithLocation(28, 11), // (29,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'short?' // W(i != default(short?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != default(short?)").WithArguments("true", "int", "short?").WithLocation(29, 11), // (32,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == default(Guid?)").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(32, 11), // (33,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != default(Guid?)); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != default(Guid?)").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(33, 11), // (37,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i == new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == new sbyte?()").WithArguments("false", "int", "sbyte?").WithLocation(37, 11), // (38,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'sbyte?' // W(i != new sbyte?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i != new sbyte?()").WithArguments("true", "int", "sbyte?").WithLocation(38, 11), // (41,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g == new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g == new Guid?()").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(41, 11), // (42,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(g != new Guid?()); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "g != new Guid?()").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(42, 11), // (49,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null == i").WithArguments("false", "int", "int?").WithLocation(49, 11), // (50,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != i").WithArguments("true", "int", "int?").WithLocation(50, 11), // (53,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(53, 11), // (54,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(null != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "null != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(54, 11), // (58,11): warning CS0472: The result of the expression is always 'false' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) == i").WithArguments("false", "long", "long?").WithLocation(58, 11), // (59,11): warning CS0472: The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?' // W(default(long?) != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(long?) != i").WithArguments("true", "long", "long?").WithLocation(59, 11), // (62,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(62, 11), // (63,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(default(Guid?) != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(Guid?) != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(63, 11), // (67,11): warning CS0472: The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() == i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() == i").WithArguments("false", "double", "double?").WithLocation(67, 11), // (68,11): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?' // W(new double?() != i); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new double?() != i").WithArguments("true", "double", "double?").WithLocation(68, 11), // (71,11): warning CS8073: The result of the expression is always 'false' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() == g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() == g").WithArguments("false", "System.Guid", "System.Guid?").WithLocation(71, 11), // (72,11): warning CS8073: The result of the expression is always 'true' since a value of type 'System.Guid' is never equal to 'null' of type 'System.Guid?' // W(new Guid?() != g); // CS0472 Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new Guid?() != g").WithArguments("true", "System.Guid", "System.Guid?").WithLocation(72, 11), // (84,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)1 == null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(84, 11), // (85,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(null != (E?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (E?)1").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(85, 11), // (87,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)1 == null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)1 == null").WithArguments("false", "int", "int?").WithLocation(87, 11), // (88,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W(null != (int?)1); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "null != (int?)1").WithArguments("true", "int", "int?").WithLocation(88, 11), // (92,11): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // W(0 == (int?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (int?)null").WithArguments("false", "int", "int?").WithLocation(92, 11), // (93,11): warning CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type 'int?' // W((int?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(int?)null != 0").WithArguments("true", "int", "int?").WithLocation(93, 11), // (95,11): warning CS0472: The result of the expression is always 'false' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W(0 == (E?)null); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "0 == (E?)null").WithArguments("false", "MyClass.E", "MyClass.E?").WithLocation(95, 11), // (96,11): warning CS0472: The result of the expression is always 'true' since a value of type 'MyClass.E' is never equal to 'null' of type 'MyClass.E?' // W((E?)null != 0); Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "(E?)null != 0").WithArguments("true", "MyClass.E", "MyClass.E?").WithLocation(96, 11) }; var compatibleExpected = fullExpected.Where(d => !d.Code.Equals((int)ErrorCode.WRN_NubExprIsConstBool2)).ToArray(); this.CompileAndVerify(source: text, expectedOutput: expected, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(compatibleExpected); this.CompileAndVerify(source: text, expectedOutput: expected).VerifyDiagnostics(fullExpected); } [Fact] public void CS0472WRN_NubExprIsConstBool_ConstructorInitializer() { var text = @"class A { internal A(bool b) { } } class B : A { B(int i) : base(i == null) { } }"; CreateCompilation(text).VerifyDiagnostics( // (9,21): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // B(int i) : base(i == null) Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "i == null").WithArguments("false", "int", "int?").WithLocation(9, 21)); } [Fact] public void CS0612WRN_DeprecatedSymbol() { var text = @" using System; class MyClass { [Obsolete] public static void ObsoleteMethod() { } [Obsolete] public static int ObsoleteField; } class MainClass { static public void Main() { MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated } } "; CreateCompilation(text). VerifyDiagnostics( // (17,7): warning CS0612: 'MyClass.ObsoleteMethod()' is obsolete // MyClass.ObsoleteMethod(); // CS0612 here: method is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteMethod()").WithArguments("MyClass.ObsoleteMethod()"), // (18,7): warning CS0612: 'MyClass.ObsoleteField' is obsolete // MyClass.ObsoleteField = 0; // CS0612 here: field is deprecated Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "MyClass.ObsoleteField").WithArguments("MyClass.ObsoleteField")); } [Fact, WorkItem(546062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546062")] public void CS0618WRN_DeprecatedSymbol() { var text = @" public class ConsoleStub { public static void Main(string[] args) { System.Collections.CaseInsensitiveHashCodeProvider x; System.Console.WriteLine(x); } }"; CreateCompilation(text). VerifyDiagnostics( // (6,9): warning CS0618: 'System.Collections.CaseInsensitiveHashCodeProvider' is obsolete: 'Please use StringComparer instead.' // System.Collections.CaseInsensitiveHashCodeProvider x; Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Collections.CaseInsensitiveHashCodeProvider").WithArguments("System.Collections.CaseInsensitiveHashCodeProvider", "Please use StringComparer instead."), // (7,34): error CS0165: Use of unassigned local variable 'x' // System.Console.WriteLine(x); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x")); } [WorkItem(545347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545347")] [Fact] public void CS0649WRN_UnassignedInternalField() { var text = @" using System.Collections; class MyClass { Hashtable table; // CS0649 public void Func(object o, string p) { table[p] = o; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,15): warning CS0649: Field 'MyClass.table' is never assigned to, and will always have its default value null // Hashtable table; // CS0649 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "table").WithArguments("MyClass.table", "null") ); } [Fact, WorkItem(543454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543454")] public void CS0649WRN_UnassignedInternalField_1() { var text = @" public class GenClass<T, U> { } public class Outer { internal protected class C1 { } public class C2 { } internal class Test { public GenClass<C1, C2> Fld; } public static int Main() { return 0; } }"; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Fld").WithArguments("Outer.Test.Fld", "null")); } [WorkItem(546449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546449")] [WorkItem(546949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546949")] [Fact] public void CS0652WRN_VacuousIntegralComp() { var text = @" public class Class1 { private static byte i = 0; public static void Main() { const short j = 256; if (i == j) // CS0652, 256 is out of range for byte i = 0; // However, we do not give this warning if both sides of the comparison are constants. In those // cases, we are probably in machine-generated code anyways. const byte k = 0; if (k == j) {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0652: Comparison to integral constant is useless; the constant is outside the range of type 'byte' // if (i == j) // CS0652, 256 is out of range for byte Diagnostic(ErrorCode.WRN_VacuousIntegralComp, "i == j").WithArguments("byte")); } [WorkItem(546790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546790")] [Fact] public void CS0652WRN_VacuousIntegralComp_ExplicitCast() { var text = @" using System; public class Program { public static void Main() { Int16 wSuiteMask = 0; const int VER_SUITE_WH_SERVER = 0x00008000; if (VER_SUITE_WH_SERVER == (Int32)wSuiteMask) { } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0665WRN_IncorrectBooleanAssg() { var text = @" class Test { public static void Main() { bool i = false; if (i = true) // CS0665 // try the following line instead // if (i == true) { } System.Console.WriteLine(i); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,11): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "i = true")); } [Fact, WorkItem(540777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777")] public void CS0665WRN_IncorrectBooleanAssg_ConditionalOperator() { var text = @" class Program { static int Main(string[] args) { bool a = true; System.Console.WriteLine(a); return ((a = false) ? 50 : 100); // Warning } } "; CreateCompilation(text).VerifyDiagnostics( // (8,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "a = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Contexts() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if (b = false) { } while (b = false) { } do { } while (b = false); for (; b = false; ) { } System.Console.WriteLine((b = false) ? 1 : 2); } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // while (b = false) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (10,23): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // do { } while (b = false); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (11,16): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // for (; b = false; ) { } Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (12,35): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // System.Console.WriteLine((b = false) ? 1 : 2); Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact] public void CS0665WRN_IncorrectBooleanAssg_Nesting() { var text = @" class C { static void Main(string[] args) { bool b = args.Length > 1; if ((b = false)) { } // parens - warn if (((b = false))) { } // more parens - warn if (M(b = false)) { } // call - do not warn if ((bool)(b = false)) { } // cast - do not warn if ((b = false) || (b = true)) { } // binary operator - do not warn B bb = new B(); if (bb = false) { } // implicit conversion - do not warn } static bool M(bool b) { return b; } } class B { public static implicit operator B(bool b) { return new B(); } public static bool operator true(B b) { return true; } public static bool operator false(B b) { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,14): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if ((b = false)) { } // parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (9,15): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // if (((b = false))) { } // more parens - warn Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false")); } [Fact, WorkItem(909, "https://github.com/dotnet/roslyn/issues/909")] public void CS0675WRN_BitwiseOrSignExtend() { var text = @" public class sign { public static void Main() { int i32_hi = 1; int i32_lo = 1; ulong u64 = 1; sbyte i08 = 1; short i16 = -1; object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 object v2 = (ulong)i32_hi | u64; // CS0675 object v3 = (ulong)i32_hi | (ulong)i32_lo; // No warning; the sign extension bits are the same on both sides. object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 object v5 = (int)i08 | (int)i32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v6 = (((ulong)i32_hi) << 32) | (uint) i32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v7 = 0x0000BEEFU | (uint)i16; object v8 = 0xFFFFBEEFU | (uint)i16; object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 // We should do the exact same logic for nullables. int? ni32_hi = 1; int? ni32_lo = 1; ulong? nu64 = 1; sbyte? ni08 = 1; short? ni16 = -1; object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 object v12 = (ulong?)ni32_hi | nu64; // CS0675 object v13 = (ulong?)ni32_hi | (ulong?)ni32_lo; // No warning; the sign extension bits are the same on both sides. object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 object v15 = (int?)ni08 | (int?)ni32_lo; // No warning; sign extension is considered to be 'expected' when casting. object v16 = (((ulong?)ni32_hi) << 32) | (uint?) ni32_lo; // No warning; we've cast to a smaller unsigned type first. // We suppress the warning if the bits that are going to be wiped out are known already to be all zero or all one: object v17 = 0x0000BEEFU | (uint?)ni16; object v18 = 0xFFFFBEEFU | (uint?)ni16; object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 } } class Test { static void Main() { long bits = 0; for (int i = 0; i < 32; i++) { if (i % 2 == 0) { bits |= (1 << i); bits = bits | (1 << i); } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v1 = (((long)i32_hi) << 32) | i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long)i32_hi) << 32) | i32_lo"), // (13,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v2 = (ulong)i32_hi | u64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)i32_hi | u64"), // (15,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v4 = (ulong)(uint)(ushort)i08 | (ulong)i32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong)(uint)(ushort)i08 | (ulong)i32_lo"), // (21,19): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v9 = 0xDEADBEEFU | (uint)i16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint)i16"), // (31,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v11 = (((long?)ni32_hi) << 32) | ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(((long?)ni32_hi) << 32) | ni32_lo"), // (32,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v12 = (ulong?)ni32_hi | nu64; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)ni32_hi | nu64"), // (34,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v14 = (ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "(ulong?)(uint?)(ushort?)ni08 | (ulong?)ni32_lo"), // (40,20): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // object v19 = 0xDEADBEEFU | (uint?)ni16; // CS0675 Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "0xDEADBEEFU | (uint?)ni16"), // (53,17): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits |= (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits |= (1 << i)").WithLocation(53, 17), // (54,24): warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first // bits = bits | (1 << i); Diagnostic(ErrorCode.WRN_BitwiseOrSignExtend, "bits | (1 << i)").WithLocation(54, 24) ); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose01() { CreateCompilation(@" using System; public class ValidBase : IDisposable { public void Dispose() { } } public class Logger { public static void dummy() { ValidBase vb = null; using (vb) { vb = null; // CS0728 } vb = null; } public static void Main() { } }") .VerifyDiagnostics( // (15,13): warning CS0728: Possibly incorrect assignment to local 'vb' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local. Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "vb").WithArguments("vb")); } [Fact] public void CS0728WRN_AssignmentToLockOrDispose02() { CreateCompilation( @"class D : System.IDisposable { public void Dispose() { } } class C { static void M() { D d = new D(); using (d) { N(ref d); } lock (d) { N(ref d); } } static void N(ref D d) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(12, 19), Diagnostic(ErrorCode.WRN_AssignmentToLockOrDispose, "d").WithArguments("d").WithLocation(16, 19)); } [WorkItem(543615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543615"), WorkItem(546550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546550")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CS0811ERR_DebugFullNameTooLong() { var text = @" using System; using System.Collections.Generic; namespace TestNamespace { using VeryLong = List<List<List<List<List<List<List<List<List<List<List<List<List <List<List<List<List<List<List<List<List<List<List<List<List<List<List<List<int>>>>>>>>>>>>>>>>>>>>>>>>>>>>; // CS0811 class Test { static int Main() { VeryLong goo = null; Console.WriteLine(goo); return 1; } } } "; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.DebugExe); var exebits = new System.IO.MemoryStream(); var pdbbits = new System.IO.MemoryStream(); var result = compilation.Emit(exebits, pdbbits, options: TestOptions.NativePdbEmit); result.Diagnostics.Verify( // (12,20): warning CS0811: The fully qualified name for 'AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is too long for debug information. Compile without '/debug' option. // static int Main() Diagnostic(ErrorCode.WRN_DebugFullNameTooLong, "Main").WithArguments("AVeryLong TSystem.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Collections.Generic.List`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(12, 20)); } [Fact] public void CS1058WRN_UnreachableGeneralCatch() { var text = @"class C { static void M() { try { } catch (System.Exception) { } catch (System.IO.IOException) { } catch { } try { } catch (System.IO.IOException) { } catch (System.Exception) { } catch { } } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_UnreachableCatch, "System.IO.IOException").WithArguments("System.Exception").WithLocation(7, 16), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(8, 9), Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch").WithLocation(12, 9)); } // [Fact(Skip = "11486")] // public void CS1060WRN_UninitializedField() // { // var text = @" //namespace CS1060 //{ // public class U // { // public int i; // } // // public struct S // { // public U u; // } // public class Test // { // static void Main() // { // S s; // s.u.i = 5; // CS1060 // } // } //} //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_UninitializedField, Line = 18, Column = 13, IsWarning = true } }); // } // [Fact()] // public void CS1064ERR_DebugFullNameTooLong() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = 1064, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact] public void CS1570WRN_XMLParseError() { var text = @" namespace ns { // the following line generates CS1570 /// <summary> returns true if < 5 </summary> // try this instead // /// <summary> returns true if &lt;5 </summary> public class MyClass { public static void Main () { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (5,35): warning CS1570: XML comment has badly formed XML -- 'An identifier was expected.' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, ""), // (5,35): warning CS1570: XML comment has badly formed XML -- '5' // /// <summary> returns true if < 5 </summary> Diagnostic(ErrorCode.WRN_XMLParseError, " ").WithArguments("5"), // (11,26): warning CS1591: Missing XML comment for publicly visible type or member 'ns.MyClass.Main()' // public static void Main () Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("ns.MyClass.Main()")); } [Fact] public void CS1571WRN_DuplicateParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>An initial.</param> /// <param name='Int1'>Used to indicate status.</param> // CS1571 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,15): warning CS1571: XML comment has a duplicate param tag for 'Int1' // /// <param name='Int1'>Used to indicate status.</param> // CS1571 Diagnostic(ErrorCode.WRN_DuplicateParamTag, "name='Int1'").WithArguments("Int1")); } [Fact] public void CS1572WRN_UnmatchedParamTag() { var text = @" /// <summary>help text</summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// <param name='Char1'>Used to indicate status.</param> /// <param name='Char2'>???</param> // CS1572 public static void MyMethod(int Int1, char Char1) { } /// <summary>help text</summary> public static void Main () { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,21): warning CS1572: XML comment has a param tag for 'Char2', but there is no parameter by that name // /// <param name='Char2'>???</param> // CS1572 Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Char2").WithArguments("Char2")); } [Fact] public void CS1573WRN_MissingParamTag() { var text = @" /// <summary> </summary> public class MyClass { /// <param name='Int1'>Used to indicate status.</param> /// enter a comment for Char1? public static void MyMethod(int Int1, char Char1) { } /// <summary> </summary> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (7,48): warning CS1573: Parameter 'Char1' has no matching param tag in the XML comment for 'MyClass.MyMethod(int, char)' (but other parameters do) // public static void MyMethod(int Int1, char Char1) Diagnostic(ErrorCode.WRN_MissingParamTag, "Char1").WithArguments("Char1", "MyClass.MyMethod(int, char)")); } [Fact] public void CS1574WRN_BadXMLRef() { var text = @" /// <see cref=""D""/> public class C { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,16): warning CS1574: XML comment has cref attribute 'D' that could not be resolved // /// <see cref="D"/> Diagnostic(ErrorCode.WRN_BadXMLRef, "D").WithArguments("D")); } [Fact] public void CS1580WRN_BadXMLRefParamType() { var text = @" /// <seealso cref=""Test(i)""/> // CS1580 public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public void Test(int i) { } /// <summary>help text</summary> public void Test(char i) { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1580: Invalid type for parameter 'i' in XML comment cref attribute: 'Test(i)' // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRefParamType, "i").WithArguments("i", "Test(i)"), // (2,20): warning CS1574: XML comment has cref attribute 'Test(i)' that could not be resolved // /// <seealso cref="Test(i)"/> // CS1580 Diagnostic(ErrorCode.WRN_BadXMLRef, "Test(i)").WithArguments("Test(i)")); } [Fact] public void CS1581WRN_BadXMLRefReturnType() { var text = @" /// <summary>help text</summary> public class MyClass { /// <summary>help text</summary> public static void Main() { } /// <summary>help text</summary> public static explicit operator int(MyClass f) { return 0; } } /// <seealso cref=""MyClass.explicit operator intt(MyClass)""/> // CS1581 public class MyClass2 { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (15,20): warning CS1581: Invalid return type in XML comment cref attribute // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRefReturnType, "intt").WithArguments("intt", "MyClass.explicit operator intt(MyClass)"), // (15,20): warning CS1574: XML comment has cref attribute 'MyClass.explicit operator intt(MyClass)' that could not be resolved // /// <seealso cref="MyClass.explicit operator intt(MyClass)"/> // CS1581 Diagnostic(ErrorCode.WRN_BadXMLRef, "MyClass.explicit operator intt(MyClass)").WithArguments("explicit operator intt(MyClass)")); } [Fact] public void CS1584WRN_BadXMLRefSyntax() { var text = @" /// public class MyClass1 { /// public static MyClass1 operator /(MyClass1 a1, MyClass1 a2) { return null; } /// <seealso cref=""MyClass1.operator@""/> public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (10,24): warning CS1584: XML comment has syntactically incorrect cref attribute 'MyClass1.operator@' // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "MyClass1.operator").WithArguments("MyClass1.operator@"), // (10,41): warning CS1658: Overloadable operator expected. See also error CS1037. // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.WRN_ErrorOverride, "@").WithArguments("Overloadable operator expected", "1037"), // (10,41): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @ // /// <seealso cref="MyClass1.operator@"/> Diagnostic(ErrorCode.ERR_ExpectedVerbatimLiteral, "")); } [Fact] public void CS1587WRN_UnprocessedXMLComment() { var text = @" /// <summary>test</summary> // CS1587, tag not allowed on namespace namespace MySpace { class MyClass { public static void Main() { } } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnprocessedXMLComment, "/")); } [Fact] public void CS1589WRN_NoResolver() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; var c = CreateCompilation( new[] { Parse(text, options: TestOptions.RegularWithDocumentationComments) }, options: TestOptions.ReleaseDll.WithXmlReferenceResolver(null)); c.VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- References to XML documents are not supported. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "References to XML documents are not supported.")); } [Fact] public void CS1589WRN_FailedInclude() { var text = @" /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' /> // CS1589 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1589: Unable to include XML fragment 'MyDocs/MyMembers[@name="test"]/' of file 'CS1589.doc' -- Unable to find the specified file. // /// <include file='CS1589.doc' path='MyDocs/MyMembers[@name="test"]/' /> // CS1589 Diagnostic(ErrorCode.WRN_FailedInclude, @"<include file='CS1589.doc' path='MyDocs/MyMembers[@name=""test""]/' />"). WithArguments("CS1589.doc", @"MyDocs/MyMembers[@name=""test""]/", "File not found.")); } [Fact] public void CS1590WRN_InvalidInclude() { var text = @" /// <include path='MyDocs/MyMembers[@name=""test""]/*' /> // CS1590 class Test { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,5): warning CS1590: Invalid XML include element -- Missing file attribute // /// <include path='MyDocs/MyMembers[@name="test"]/*' /> // CS1590 Diagnostic(ErrorCode.WRN_InvalidInclude, @"<include path='MyDocs/MyMembers[@name=""test""]/*' />").WithArguments("Missing file attribute")); } [Fact] public void CS1591WRN_MissingXMLComment() { var text = @" /// text public class Test { // /// text public static void Main() // CS1591 { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'Test.Main()' // public static void Main() // CS1591 Diagnostic(ErrorCode.WRN_MissingXMLComment, "Main").WithArguments("Test.Main()")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/18610")] public void CS1592WRN_XMLParseIncludeError() { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText("&"); var sourceTemplate = @" /// <include file='{0}' path='element'/> public class Test {{ }} "; var comp = CreateCompilationWithMscorlib40AndDocumentationComments(string.Format(sourceTemplate, xmlFile.Path)); using (new EnsureEnglishUICulture()) { comp.VerifyDiagnostics( // dcf98d2ac30a.xml(1,1): warning CS1592: Badly formed XML in included comments file -- 'Data at the root level is invalid.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Data at the root level is invalid.")); } } [Fact] public void CS1658WRN_ErrorOverride() { var text = @" /// <seealso cref=""""/> public class Test { /// public static int Main() { return 0; } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,20): warning CS1584: XML comment has syntactically incorrect cref attribute '' // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, @"""").WithArguments(""), // (2,20): warning CS1658: Identifier expected. See also error CS1001. // /// <seealso cref=""/> Diagnostic(ErrorCode.WRN_ErrorOverride, @"""").WithArguments("Identifier expected", "1001")); } // TODO (tomat): Also fix AttributeTests.DllImport_AttributeRedefinition [Fact(Skip = "530377"), WorkItem(530377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530377"), WorkItem(685159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/685159")] public void CS1685WRN_MultiplePredefTypes() { var text = @" public static class C { public static void Extension(this int X) {} }"; // include both mscorlib 4.0 and System.Core 3.5, both of which contain ExtensionAttribute // These libraries are not yet in our suite CreateEmptyCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.WRN_MultiplePredefTypes, "")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField() { var text = @" using System; class WarningCS1690 : MarshalByRefObject { int i = 5; public static void Main() { WarningCS1690 e = new WarningCS1690(); e.i.ToString(); // CS1690 int i = e.i; i.ToString(); e.i = i; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_CallOnNonAgileField, Line = 11, Column = 9, IsWarning = true } }); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Variations() { var text = @" using System; struct S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (19,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event = null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (20,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Event += null; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (21,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.Property++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (22,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s[0]++; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (23,13): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // w.s.M(); Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (24,24): warning CS1690: Accessing a member on 'S.WarningCS1690.s' may cause a runtime exception because it is a field of a marshal-by-reference class // Action a = w.s.M; Diagnostic(ErrorCode.WRN_CallOnNonAgileField, "w.s").WithArguments("S.WarningCS1690.s"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } [Fact, WorkItem(530379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530379")] public void CS1690WRN_CallOnNonAgileField_Class() { var text = @" using System; class S { public event Action Event; public int Field; public int Property { get; set; } public int this[int x] { get { return 0; } set { } } public void M() { } class WarningCS1690 : MarshalByRefObject { S s; public static void Main() { WarningCS1690 w = new WarningCS1690(); w.s.Event = null; w.s.Event += null; w.s.Property++; w.s[0]++; w.s.M(); Action a = w.s.M; } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,11): warning CS0649: Field 'S.WarningCS1690.s' is never assigned to, and will always have its default value null // S s; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "s").WithArguments("S.WarningCS1690.s", "null"), // (7,16): warning CS0649: Field 'S.Field' is never assigned to, and will always have its default value 0 // public int Field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field").WithArguments("S.Field", "0"), // (6,25): warning CS0414: The field 'S.Event' is assigned but its value is never used // public event Action Event; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Event").WithArguments("S.Event")); } // [Fact()] // public void CS1707WRN_DelegateNewMethBind() // { // var text = @" //"; // DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_DelegateNewMethBind, Line = 7, Column = 5, IsWarning = true } } // ); // } [Fact(), WorkItem(530384, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530384")] public void CS1709WRN_EmptyFileName() { var text = @" class Test { static void Main() { #pragma checksum """" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" """" // CS1709 } } "; //EDMAURER no longer giving this low-value warning. CreateCompilation(text). VerifyDiagnostics(); //VerifyDiagnostics(Diagnostic(ErrorCode.WRN_EmptyFileName, @"""")); } [Fact] public void CS1710WRN_DuplicateTypeParamTag() { var text = @" class Stack<ItemType> { } /// <typeparam name=""MyType"">can be an int</typeparam> /// <typeparam name=""MyType"">can be an int</typeparam> class MyStackWrapper<MyType> { // Open constructed type Stack<MyType>. Stack<MyType> stack; public MyStackWrapper(Stack<MyType> s) { stack = s; } } class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (6,16): warning CS1710: XML comment has a duplicate typeparam tag for 'MyType' // /// <typeparam name="MyType">can be an int</typeparam> Diagnostic(ErrorCode.WRN_DuplicateTypeParamTag, @"name=""MyType""").WithArguments("MyType")); } [Fact] public void CS1711WRN_UnmatchedTypeParamTag() { var text = @" ///<typeparam name=""WrongName"">can be an int</typeparam> class CMain { public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (2,21): warning CS1711: XML comment has a typeparam tag for 'WrongName', but there is no type parameter by that name // ///<typeparam name="WrongName">can be an int</typeparam> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "WrongName").WithArguments("WrongName")); } [Fact] public void CS1712WRN_MissingTypeParamTag() { var text = @" ///<summary>A generic list delegate.</summary> ///<typeparam name=""T"">The first type stored by the list.</typeparam> public delegate void List<T,W>(); /// public class Test { /// public static void Main() { } } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (4,29): warning CS1712: Type parameter 'W' has no matching typeparam tag in the XML comment on 'List<T, W>' (but other type parameters do) // public delegate void List<T,W>(); Diagnostic(ErrorCode.WRN_MissingTypeParamTag, "W").WithArguments("W", "List<T, W>")); } [Fact] public void CS1717WRN_AssignmentToSelf() { var text = @" public class Test { public static void Main() { int x = 0; x = x; // CS1717 } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_AssignmentToSelf, Line = 7, Column = 7, IsWarning = true } }); } [WorkItem(543470, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543470")] [Fact] public void CS1717WRN_AssignmentToSelf02() { var text = @" class C { void M(object p) { object oValue = p; if (oValue is int) { //(SQL 9.0) 653716 + common sense oValue = (double) ((int) oValue); } } }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1717WRN_AssignmentToSelf03() { var text = @" using System; class Program { int f; event Action e; void Test(int p) { int l = 0; l = l; p = p; f = f; e = e; } } "; CreateCompilation(text).VerifyDiagnostics( // (13,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = l"), // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // p = p; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "p = p"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = f"), // (16,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = e")); } [Fact] public void CS1717WRN_AssignmentToSelf04() { var text = @" using System; class Program { int f; event Action e; static int sf; static event Action se; void Test(Program other) { f = this.f; e = this.e; f = other.f; //fine e = other.e; //fine sf = sf; se = se; sf = Program.sf; se = Program.se; } } "; CreateCompilation(text).VerifyDiagnostics( // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = this.f; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = this.f"), // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // e = this.e; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "e = this.e"), // (20,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = sf"), // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = se"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sf = Program.sf; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sf = Program.sf"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // se = Program.se; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "se = Program.se")); } [Fact] public void CS1717WRN_AssignmentToSelf05() { var text = @" using System.Linq; class Program { static void Main(string[] args) { var unused = from x in args select x = x; } } "; // CONSIDER: dev11 reports WRN_AssignmentToSelf. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,44): error CS1947: Range variable 'x' cannot be assigned to -- it is read only // var unused = from x in args select x = x; Diagnostic(ErrorCode.ERR_QueryRangeVariableReadOnly, "x").WithArguments("x")); } [Fact] public void CS1717WRN_AssignmentToSelf06() { var text = @" class C { void M( byte b, sbyte sb, short s, ushort us, int i, uint ui, long l, ulong ul, float f, double d, decimal m, bool bo, object o, C cl, S st) { b = (byte)b; sb = (sbyte)sb; s = (short)s; us = (ushort)us; i = (int)i; ui = (uint)ui; l = (long)l; ul = (ulong)ul; f = (float)f; // Not reported by dev11. d = (double)d; // Not reported by dev11. m = (decimal)m; bo = (bool)bo; o = (object)o; cl = (C)cl; st = (S)st; } } struct S { } "; // CONSIDER: dev11 does not strip off float or double identity-conversions and, thus, // does not warn about those assignments. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (21,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b = (byte)b; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b = (byte)b"), // (22,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // sb = (sbyte)sb; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "sb = (sbyte)sb"), // (23,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // s = (short)s; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "s = (short)s"), // (24,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // us = (ushort)us; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "us = (ushort)us"), // (25,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // i = (int)i; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "i = (int)i"), // (26,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ui = (uint)ui; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ui = (uint)ui"), // (27,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // l = (long)l; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "l = (long)l"), // (28,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // ul = (ulong)ul; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "ul = (ulong)ul"), // (29,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // f = (float)f; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "f = (float)f"), // (30,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // d = (double)d; // Not reported by dev11. Diagnostic(ErrorCode.WRN_AssignmentToSelf, "d = (double)d"), // (31,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // m = (decimal)m; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "m = (decimal)m"), // (32,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // bo = (bool)bo; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "bo = (bool)bo"), // (33,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // o = (object)o; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "o = (object)o"), // (34,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // cl = (C)cl; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "cl = (C)cl"), // (35,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // st = (S)st; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "st = (S)st")); } [Fact, WorkItem(546493, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546493")] public void CS1718WRN_ComparisonToSelf() { var text = @" class Tester { static int j = 123; static void Main() { int i = 0; if (i == i) i++; if (j == Tester.j) j++; } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (i == i) i++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "i == i"), // (9,13): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (j == Tester.j) j++; Diagnostic(ErrorCode.WRN_ComparisonToSelf, "j == Tester.j")); } [Fact, WorkItem(580501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580501")] public void CS1718WRN_ComparisonToSelf2() { var text = @" using System.Linq; class Tester { static void Main() { var q = from int x1 in new[] { 2, 9, 1, 8, } where x1 > x1 // CS1718 select x1; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,15): warning CS1718: Comparison made to same variable; did you mean to compare something else? // where x1 > x1 // CS1718 Diagnostic(ErrorCode.WRN_ComparisonToSelf, "x1 > x1")); } [Fact] public void CS1720WRN_DotOnDefault01() { var source = @"class A { internal object P { get; set; } } interface I { object P { get; set; } } static class C { static void M<T1, T2, T3, T4, T5, T6, T7>() where T2 : new() where T3 : struct where T4 : class where T5 : T1 where T6 : A where T7 : I { default(int).GetHashCode(); default(object).GetHashCode(); default(T1).GetHashCode(); default(T2).GetHashCode(); default(T3).GetHashCode(); default(T4).GetHashCode(); default(T5).GetHashCode(); default(T6).GetHashCode(); default(T7).GetHashCode(); default(T6).P = null; default(T7).P = null; default(int).E(); default(object).E(); default(T1).E(); default(T2).E(); default(T3).E(); default(T4).E(); default(T5).E(); default(T6).E(); // Dev10 (incorrectly) reports CS1720 default(T7).E(); } static void E(this object o) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (20,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object' is null // default(object).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object).GetHashCode").WithArguments("object").WithLocation(20, 9), // (24,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null // default(T4).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4).GetHashCode").WithArguments("T4").WithLocation(24, 9), // (26,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).GetHashCode(); Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).GetHashCode").WithArguments("T6").WithLocation(26, 9), // (28,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T6' is null // default(T6).P = null; Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T6).P").WithArguments("T6").WithLocation(28, 9)); CreateCompilationWithMscorlib40(source, references: new[] { Net40.SystemCore }, options: TestOptions.ReleaseDll.WithNullableContextOptions(NullableContextOptions.Disable)).VerifyDiagnostics( ); } [Fact] public void CS1720WRN_DotOnDefault02() { var source = @"class A { internal object this[object index] { get { return null; } set { } } } struct S { internal object this[object index] { get { return null; } set { } } } interface I { object this[object index] { get; set; } } class C { unsafe static void M<T1, T2, T3, T4>() where T1 : A where T2 : I where T3 : struct, I where T4 : class, I { object o; o = default(int*)[0]; o = default(A)[0]; o = default(S)[0]; o = default(I)[0]; o = default(object[])[0]; o = default(T1)[0]; o = default(T2)[0]; o = default(T3)[0]; o = default(T4)[0]; default(int*)[1] = 1; default(A)[1] = o; default(I)[1] = o; default(object[])[1] = o; default(T1)[1] = o; default(T2)[1] = o; default(T3)[1] = o; default(T4)[1] = o; } }"; CreateCompilation(source, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (23,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[0]").WithArguments("A").WithLocation(23, 13), // (25,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[0]").WithArguments("I").WithLocation(25, 13), // (26,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[0]").WithArguments("object[]").WithLocation(26, 13), // (27,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[0]").WithArguments("T1").WithLocation(27, 13), // (30,13): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[0]").WithArguments("T4").WithLocation(30, 13), // (32,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'A' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(A)[1]").WithArguments("A").WithLocation(32, 9), // (33,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'I' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(I)[1]").WithArguments("I").WithLocation(33, 9), // (34,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'object[]' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(object[])[1]").WithArguments("object[]").WithLocation(34, 9), // (35,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T1' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T1)[1]").WithArguments("T1").WithLocation(35, 9), // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9), // Incorrect? See CS0131ERR_AssgLvalueExpected03 unit test. // (38,9): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'T4' is null Diagnostic(ErrorCode.WRN_DotOnDefault, "default(T4)[1]").WithArguments("T4").WithLocation(38, 9)); CreateCompilation(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (37,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // default(T3)[1] = o; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "default(T3)[1]").WithLocation(37, 9)); } [Fact] public void CS1720WRN_DotOnDefault03() { var source = @"static class A { static void Main() { System.Console.WriteLine(default(string).IsNull()); } internal static bool IsNull(this string val) { return (object)val == null; } } "; CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // Do not report the following warning: // (5,34): warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null // System.Console.WriteLine(default(string).IsNull()); // Diagnostic(ErrorCode.WRN_DotOnDefault, "default(string).IsNull").WithArguments("string").WithLocation(5, 34) ); CompileAndVerifyWithMscorlib40(source, expectedOutput: "True", references: new[] { Net40.SystemCore }).VerifyDiagnostics(); } [Fact] public void CS1723WRN_BadXMLRefTypeVar() { var text = @" ///<summary>A generic list class.</summary> ///<see cref=""T"" /> // CS1723 public class List<T> { } "; CreateCompilationWithMscorlib40AndDocumentationComments(text).VerifyDiagnostics( // (3,15): warning CS1723: XML comment has cref attribute 'T' that refers to a type parameter // ///<see cref="T" /> // CS1723 Diagnostic(ErrorCode.WRN_BadXMLRefTypeVar, "T").WithArguments("T")); } [Fact] public void CS1974WRN_DynamicDispatchToConditionalMethod() { var text = @" using System.Diagnostics; class Myclass { static void Main() { dynamic d = null; // Warning because Goo might be conditional. Goo(d); // No warning; only the two-parameter Bar is conditional. Bar(d); } [Conditional(""DEBUG"")] static void Goo(string d) {} [Conditional(""DEBUG"")] static void Bar(int x, int y) {} static void Bar(string x) {} }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(text); comp.VerifyDiagnostics( // (9,9): warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime because one or more applicable overloads are conditional methods. // Goo(d); Diagnostic(ErrorCode.WRN_DynamicDispatchToConditionalMethod, "Goo(d)").WithArguments("Goo")); } [Fact] public void CS1981WRN_IsDynamicIsConfusing() { var text = @" public class D : C { } public class C { public static int Main() { // is dynamic bool bi = 123 is dynamic; // dynamicType is valueType dynamic i2 = 123; bi = i2 is int; // dynamicType is refType dynamic c = new D(); bi = c is C; dynamic c2 = new C(); bi = c is C; // valueType as dynamic int i = 123 as dynamic; // refType as dynamic dynamic c3 = new D() as dynamic; // dynamicType as dynamic dynamic s = ""asd""; string s2 = s as dynamic; // default(dynamic) dynamic d = default(dynamic); // dynamicType as valueType : generate error int k = i2 as int; // dynamicType as refType C c4 = c3 as C; return 0; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,19): warning CS1981: Using 'is' to test compatibility with 'dynamic' // is essentially identical to testing compatibility with 'Object' and will // succeed for all non-null values Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, "123 is dynamic").WithArguments("is", "dynamic", "Object"), // (7,19): warning CS0183: The given expression is always of the provided ('dynamic') type Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "123 is dynamic").WithArguments("dynamic"), // (27,17): error CS0077: The as operator must be used with a reference type // or nullable type ('int' is a non-nullable value type) Diagnostic(ErrorCode.ERR_AsMustHaveReferenceType, "i2 as int").WithArguments("int"), // (26,17): warning CS0219: The variable 'd' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "d").WithArguments("d")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName() { var text = @" class C<T> { void M(System.Type t) { M(typeof(C<C<>>)); //unbound inside bound M(typeof(C<>[])); //array of unbound M(typeof(C<>.D<int>)); //unbound containing bound M(typeof(C<int>.D<>)); //bound containing unbound M(typeof(D<,>[])); //multiple type parameters } class D<U> { } } class D<T, U> {}"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (7,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (8,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "C<>"), // (9,25): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<>"), // (10,18): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "D<,>")); } [Fact] public void CS7003ERR_UnexpectedUnboundGenericName_Nested() { var text = @" class Outer<T> { public static void Print() { System.Console.WriteLine(typeof(Inner<>)); System.Console.WriteLine(typeof(Inner<T>)); System.Console.WriteLine(typeof(Inner<int>)); System.Console.WriteLine(typeof(Outer<>.Inner<>)); System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003 System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<T>.Inner<T>)); System.Console.WriteLine(typeof(Outer<T>.Inner<int>)); System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003 System.Console.WriteLine(typeof(Outer<int>.Inner<T>)); System.Console.WriteLine(typeof(Outer<int>.Inner<int>)); } class Inner<U> { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (11,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (12,41): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>"), // (14,50): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (18,52): error CS7003: Unexpected use of an unbound generic name Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>")); } [Fact(), WorkItem(529583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529583")] public void CS7003ERR_UnexpectedUnboundGenericName_Attributes() { var text = @" using System; class Outer<T> { public class Inner<U> { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr : Attribute { public Attr(Type t) { } } [Attr(typeof(Outer<>.Inner<>))] [Attr(typeof(Outer<int>.Inner<>))] [Attr(typeof(Outer<>.Inner<int>))] [Attr(typeof(Outer<int>.Inner<int>))] public class Test { public static void Main() { } }"; // NOTE: Dev10 reports CS1031 (type expected) - CS7003 is new. CreateCompilation(text).VerifyDiagnostics( // (21,25): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<int>.Inner<>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Inner<>"), // (22,14): error CS7003: Unexpected use of an unbound generic name // [Attr(typeof(Outer<>.Inner<int>))] Diagnostic(ErrorCode.ERR_UnexpectedUnboundGenericName, "Outer<>")); } [Fact] public void CS7013WRN_MetadataNameTooLong() { var text = @" namespace Namespace1.Namespace2 { public interface I<T> { void Goo(); } public class OuterGenericClass<T, S> { public class NestedClass : OuterGenericClass<NestedClass, NestedClass> { } public class C : I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass> { void I<NestedClass.NestedClass.NestedClass.NestedClass.NestedClass>.Goo() { } } } } "; // This error will necessarily have a very long error string. CreateCompilation(text).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Goo").WithArguments("Namespace1.Namespace2.I<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass,Namespace1.Namespace2.OuterGenericClass<Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass,Namespace1.Namespace2.OuterGenericClass<T,S>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.NestedClass>.Goo")); } #endregion #region shotgun tests [Fact] public void DelegateCreationBad() { var text = @" namespace CSSample { class Program { static void Main(string[] args) { } delegate void D1(); delegate void D2(); delegate int D3(int x); static D1 d1; static D2 d2; static D3 d3; internal virtual void V() { } void M() { } static void S() { } static int M2(int x) { return x; } static void F(Program p) { // Error cases d1 = new D1(2 + 2); d1 = new D1(d3); d1 = new D1(2, 3); d1 = new D1(x: 3); d1 = new D1(M2); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (28,25): error CS0149: Method name expected // d1 = new D1(2 + 2); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2 + 2").WithLocation(28, 25), // (29,18): error CS0123: No overload for 'Program.D3.Invoke(int)' matches delegate 'Program.D1' // d1 = new D1(d3); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(d3)").WithArguments("CSSample.Program.D3.Invoke(int)", "CSSample.Program.D1").WithLocation(29, 18), // (30,25): error CS0149: Method name expected // d1 = new D1(2, 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "2, 3").WithLocation(30, 25), // (31,28): error CS0149: Method name expected // d1 = new D1(x: 3); Diagnostic(ErrorCode.ERR_MethodNameExpected, "3").WithLocation(31, 28), // (32,18): error CS0123: No overload for 'M2' matches delegate 'Program.D1' // d1 = new D1(M2); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D1(M2)").WithArguments("M2", "CSSample.Program.D1").WithLocation(32, 18), // (16,19): warning CS0169: The field 'Program.d2' is never used // static D2 d2; Diagnostic(ErrorCode.WRN_UnreferencedField, "d2").WithArguments("CSSample.Program.d2").WithLocation(16, 19), // (17,19): warning CS0649: Field 'Program.d3' is never assigned to, and will always have its default value null // static D3 d3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "d3").WithArguments("CSSample.Program.d3", "null").WithLocation(17, 19)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut() { var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static Func<string, string> BarP => Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref Bar); // compat var z2 = new Func<string, string>(ref Baz); // compat var z3 = new Func<string, string>(ref k); // compat var z4 = new Func<string, string>(ref x => x); var z5 = new Func<string, string>(ref Goo<string>(x => x)); var z6 = new Func<string, string>(ref BarP); var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); var z8 = new Func<string, string>(ref Program.BarP); var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); var z10 = new Func<string, string>(ref Id); // compat var z11 = new Func<string, string>(ref new(x => x)); } }"; CreateCompilation(source).VerifyDiagnostics( // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(18, 43), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,43): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "ref Program.BarP").WithArguments("Program.BarP").WithLocation(20, 43), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,47): error CS0149: Method name expected // var z1 = new Func<string, string>(ref Bar); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 47), // (14,47): error CS0149: Method name expected // var z2 = new Func<string, string>(ref Baz); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 47), // (15,47): error CS0149: Method name expected // var z3 = new Func<string, string>(ref k); // compat Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 47), // (16,47): error CS1510: A ref or out argument must be an assignable variable // var z4 = new Func<string, string>(ref x => x); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "x => x").WithLocation(16, 47), // (17,47): error CS1510: A ref or out argument must be an assignable variable // var z5 = new Func<string, string>(ref Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Goo<string>(x => x)").WithLocation(17, 47), // (18,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z6 = new Func<string, string>(ref BarP); Diagnostic(ErrorCode.ERR_RefProperty, "BarP").WithArguments("Program.BarP").WithLocation(18, 47), // (19,47): error CS1510: A ref or out argument must be an assignable variable // var z7 = new Func<string, string>(ref new Func<string, string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Func<string, string>(x => x)").WithLocation(19, 47), // (20,47): error CS0206: A property or indexer may not be passed as an out or ref parameter // var z8 = new Func<string, string>(ref Program.BarP); Diagnostic(ErrorCode.ERR_RefProperty, "Program.BarP").WithArguments("Program.BarP").WithLocation(20, 47), // (21,47): error CS1510: A ref or out argument must be an assignable variable // var z9 = new Func<string, string>(ref Program.Goo<string>(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "Program.Goo<string>(x => x)").WithLocation(21, 47), // (22,48): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref Id); // compat Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(22, 48), // (23,48): error CS1510: A ref or out value must be an assignable variable // var z11 = new Func<string, string>(ref new(x => x)); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new(x => x)").WithLocation(23, 48) ); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_Parens() { // these are allowed in compat mode without the parenthesis // with parenthesis, it behaves like strict mode var source = @" using System; public class Program { static Func<T, T> Goo<T>(Func<T, T> t) { return t; } static Func<string, string> Bar = Goo<string>(x => x); static T Id<T>(T id) => id; static void Test(Func<string, string> Baz) { var k = Bar; var z1 = new Func<string, string>(ref (Bar)); var z2 = new Func<string, string>(ref (Baz)); var z3 = new Func<string, string>(ref (k)); var z10 = new Func<string, string>(ref (Id)); // these all are still valid for compat mode, no errors should be reported for compat mode var z4 = new Func<string, string>(ref Bar); var z5 = new Func<string, string>(ref Baz); var z6 = new Func<string, string>(ref k); var z7 = new Func<string, string>(ref Id); } }"; CreateCompilation(source).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49)); CreateCompilation(source, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (13,48): error CS0149: Method name expected // var z1 = new Func<string, string>(ref (Bar)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(13, 48), // (14,48): error CS0149: Method name expected // var z2 = new Func<string, string>(ref (Baz)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(14, 48), // (15,48): error CS0149: Method name expected // var z3 = new Func<string, string>(ref (k)); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(15, 48), // (16,49): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z10 = new Func<string, string>(ref (Id)); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(16, 49), // (18,47): error CS0149: Method name expected // var z4 = new Func<string, string>(ref Bar); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Bar").WithLocation(18, 47), // (19,47): error CS0149: Method name expected // var z5 = new Func<string, string>(ref Baz); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz").WithLocation(19, 47), // (20,47): error CS0149: Method name expected // var z6 = new Func<string, string>(ref k); Diagnostic(ErrorCode.ERR_MethodNameExpected, "k").WithLocation(20, 47), // (21,47): error CS1657: Cannot pass 'Id' as a ref or out argument because it is a 'method group' // var z7 = new Func<string, string>(ref Id); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "Id").WithArguments("Id", "method group").WithLocation(21, 47)); } [Fact, WorkItem(7359, "https://github.com/dotnet/roslyn/issues/7359")] public void DelegateCreationWithRefOut_MultipleArgs() { var source = @" using System; public class Program { static Func<string, string> BarP => null; static void Test(Func<string, string> Baz) { var a = new Func<string, string>(ref Baz, Baz.Invoke); var b = new Func<string, string>(Baz, ref Baz.Invoke); var c = new Func<string, string>(ref Baz, ref Baz.Invoke); var d = new Func<string, string>(ref BarP, BarP.Invoke); var e = new Func<string, string>(BarP, ref BarP.Invoke); var f = new Func<string, string>(ref BarP, ref BarP.Invoke); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,46): error CS0149: Method name expected // var a = new Func<string, string>(ref Baz, Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, Baz.Invoke").WithLocation(8, 46), // (9,42): error CS0149: Method name expected // var b = new Func<string, string>(Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(9, 42), // (10,46): error CS0149: Method name expected // var c = new Func<string, string>(ref Baz, ref Baz.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "Baz, ref Baz.Invoke").WithLocation(10, 46), // (11,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(11, 42), // (11,46): error CS0149: Method name expected // var d = new Func<string, string>(ref BarP, BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, BarP.Invoke").WithLocation(11, 46), // (12,42): error CS0149: Method name expected // var e = new Func<string, string>(BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(12, 42), // (13,42): error CS0206: A property or indexer may not be passed as an out or ref parameter // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_RefProperty, "ref BarP").WithArguments("Program.BarP").WithLocation(13, 42), // (13,46): error CS0149: Method name expected // var f = new Func<string, string>(ref BarP, ref BarP.Invoke); Diagnostic(ErrorCode.ERR_MethodNameExpected, "BarP, ref BarP.Invoke").WithLocation(13, 46) ); } [WorkItem(538430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538430")] [Fact] public void NestedGenericAccessibility() { var text = @" public class C<T> { } public class E { class D : C<D> { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { }); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets() { var text = @" class Program { int f; int P { get; set; } int M() { return 0; } interface I { } class C { } struct S { } delegate void D(); void Test(object p) { int l = 0; Test(l<>); Test(p<>); Test(f<>); Test(P<>); Test(M<>()); Test(this.f<>); Test(this.P<>); Test(this.M<>()); System.Func<int> m; m = M<>; m = this.M<>; I<> i1 = null; C<> c1 = new C(); C c2 = new C<>(); S<> s1 = new S(); S s2 = new S<>(); D<> d1 = null; Program.I<> i2 = null; Program.C<> c3 = new Program.C(); Program.C c4 = new Program.C<>(); Program.S<> s3 = new Program.S(); Program.S s4 = new Program.S<>(); Program.D<> d2 = null; Test(default(I<>)); Test(default(C<>)); Test(default(S<>)); Test(default(Program.I<>)); Test(default(Program.C<>)); Test(default(Program.S<>)); string s; s = typeof(I<>).Name; s = typeof(C<>).Name; s = typeof(S<>).Name; s = typeof(Program.I<>).Name; s = typeof(Program.C<>).Name; s = typeof(Program.S<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (16,14): error CS0307: The variable 'l' cannot be used with type arguments // Test(l<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "l<>").WithArguments("l", "variable").WithLocation(16, 14), // (17,14): error CS0307: The variable 'object' cannot be used with type arguments // Test(p<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "p<>").WithArguments("object", "variable").WithLocation(17, 14), // (19,14): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(19, 14), // (20,14): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(20, 14), // (21,14): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(21, 14), // (23,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.f<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.f<>").WithLocation(23, 14), // (23,19): error CS0307: The field 'Program.f' cannot be used with type arguments // Test(this.f<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f<>").WithArguments("Program.f", "field").WithLocation(23, 19), // (24,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.P<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.P<>").WithLocation(24, 14), // (24,19): error CS0307: The property 'Program.P' cannot be used with type arguments // Test(this.P<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<>").WithArguments("Program.P", "property").WithLocation(24, 19), // (25,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.M<>()); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(25, 14), // (25,19): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // Test(this.M<>()); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(25, 19), // (29,13): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(29, 13), // (30,13): error CS8389: Omitting the type argument is not allowed in the current context // m = this.M<>; Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.M<>").WithLocation(30, 13), // (30,18): error CS0308: The non-generic method 'Program.M()' cannot be used with type arguments // m = this.M<>; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "M<>").WithArguments("Program.M()", "method").WithLocation(30, 18), // (32,9): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // I<> i1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(32, 9), // (33,9): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C<> c1 = new C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(33, 9), // (34,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // C c2 = new C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(34, 20), // (35,9): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S<> s1 = new S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(35, 9), // (36,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // S s2 = new S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(36, 20), // (37,9): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // D<> d1 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(37, 9), // (39,17): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Program.I<> i2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(39, 17), // (40,17): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C<> c3 = new Program.C(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(40, 17), // (41,36): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Program.C c4 = new Program.C<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(41, 36), // (42,17): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S<> s3 = new Program.S(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(42, 17), // (43,36): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Program.S s4 = new Program.S<>(); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(43, 36), // (44,17): error CS0308: The non-generic type 'Program.D' cannot be used with type arguments // Program.D<> d2 = null; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "D<>").WithArguments("Program.D", "type").WithLocation(44, 17), // (46,22): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(46, 22), // (47,22): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(47, 22), // (48,22): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(48, 22), // (50,30): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // Test(default(Program.I<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(50, 30), // (51,30): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // Test(default(Program.C<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(51, 30), // (52,30): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // Test(default(Program.S<>)); Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(52, 30), // (56,20): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(56, 20), // (57,20): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(57, 20), // (58,20): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(58, 20), // (60,28): error CS0308: The non-generic type 'Program.I' cannot be used with type arguments // s = typeof(Program.I<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "I<>").WithArguments("Program.I", "type").WithLocation(60, 28), // (61,28): error CS0308: The non-generic type 'Program.C' cannot be used with type arguments // s = typeof(Program.C<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "C<>").WithArguments("Program.C", "type").WithLocation(61, 28), // (62,28): error CS0308: The non-generic type 'Program.S' cannot be used with type arguments // s = typeof(Program.S<>).Name; Diagnostic(ErrorCode.ERR_HasNoTypeVars, "S<>").WithArguments("Program.S", "type").WithLocation(62, 28), // (4,9): warning CS0649: Field 'Program.f' is never assigned to, and will always have its default value 0 // int f; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "f").WithArguments("Program.f", "0").WithLocation(4, 9) ); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [Fact] public void EmptyAngleBrackets_Events() { var text = @" class Program { event System.Action E; event System.Action F { add { } remove { } } void Test<T>(T p) { Test(E<>); Test(this.E<>); E<> += null; //parse error F<> += null; //parse error this.E<> += null; //parse error this.F<> += null; //parse error } } "; CreateCompilation(text).VerifyDiagnostics( // Parser // (12,11): error CS1525: Invalid expression term '>' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(12, 11), // (12,13): error CS1525: Invalid expression term '+=' // E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(12, 13), // (13,11): error CS1525: Invalid expression term '>' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(13, 11), // (13,13): error CS1525: Invalid expression term '+=' // F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(13, 13), // (15,16): error CS1525: Invalid expression term '>' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(15, 16), // (15,18): error CS1525: Invalid expression term '+=' // this.E<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(15, 18), // (16,16): error CS1525: Invalid expression term '>' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(16, 16), // (16,18): error CS1525: Invalid expression term '+=' // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "+=").WithArguments("+=").WithLocation(16, 18), // Binder // (9,14): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(9, 14), // (10,14): error CS8389: Omitting the type argument is not allowed in the current context // Test(this.E<>); Diagnostic(ErrorCode.ERR_OmittedTypeArgument, "this.E<>").WithLocation(10, 14), // (10,19): error CS0307: The event 'Program.E' cannot be used with type arguments // Test(this.E<>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "E<>").WithArguments("Program.E", "event").WithLocation(10, 19), // (13,9): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(13, 9), // (16,14): error CS0079: The event 'Program.F' can only appear on the left hand side of += or -= // this.F<> += null; //parse error Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("Program.F").WithLocation(16, 14)); } [WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")] [WorkItem(542679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542679")] [Fact] public void EmptyAngleBrackets_TypeParameters() { var text = @" class Program { void Test<T>(T p) { Test(default(T<>)); string s = typeof(T<>).Name; } } "; CreateCompilation(text).VerifyDiagnostics( // (6, 24): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter"), // (7,27): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<>").WithArguments("T", "type parameter")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_TypeWithCorrectArity() { var text = @" class C<T> { static void M() { C<>.M(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic type 'C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_MethodWithCorrectArity() { var text = @" class C { static void M<T>() { M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "M<>").WithArguments("M", "method group", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedTypeWithCorrectArity() { var text = @" class A { class C<T> { static void M() { A.C<>.M(); } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,15): error CS0305: Using the generic type 'A.C<T>' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C<>").WithArguments("A.C<T>", "type", "1")); } [Fact, WorkItem(542796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542796")] public void EmptyAngleBrackets_QualifiedMethodWithCorrectArity() { var text = @" class C { static void M<T>() { C.M<>(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0305: Using the generic method group 'M' requires 1 type arguments Diagnostic(ErrorCode.ERR_BadArity, "C.M<>").WithArguments("M", "method group", "1")); } [Fact] public void NamesTooLong() { var longE = new String('e', 1024); var builder = new System.Text.StringBuilder(); builder.Append(@" class C { "); builder.AppendFormat("int {0}1;\n", longE); builder.AppendFormat("event System.Action {0}2;\n", longE); builder.AppendFormat("public void {0}3() {{ }}\n", longE); builder.AppendFormat("public void goo(int {0}4) {{ }}\n", longE); builder.AppendFormat("public string {0}5 {{ get; set; }}\n", longE); builder.AppendLine(@" } "); CreateCompilation(builder.ToString(), null, TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)).VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //event Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments(longE + 2), //backing field Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("add_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 2).WithArguments("remove_" + longE + 2), //accessor Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 3).WithArguments(longE + 3), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 4).WithArguments(longE + 4), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments(longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 5).WithArguments("<" + longE + 5 + ">k__BackingField"), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + longE + 5), Diagnostic(ErrorCode.ERR_MetadataNameTooLong, longE + 1).WithArguments(longE + 1) ); } #endregion #region regression tests [WorkItem(541605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541605")] [Fact] public void CS0019ERR_ImplicitlyTypedVariableAssignedNullCoalesceExpr() { CreateCompilation(@" class Test { public static void Main() { var p = null ?? null; //CS0019 } } ").VerifyDiagnostics( // error CS0019: Operator '??' cannot be applied to operands of type '<null>' and '<null>' Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>")); } [WorkItem(528577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528577")] [Fact(Skip = "528577")] public void CS0122ERR_InaccessibleGenericType() { CreateCompilation(@" public class Top<T> { class Outer<U> { } } public class MyClass { public static void Main() { var test = new Top<int>.Outer<string>(); } } ").VerifyDiagnostics( // (13,33): error CS0122: 'Top<int>.Outer<string>' is inaccessible due to its protection level // var test = new Top<int>.Outer<string>(); Diagnostic(ErrorCode.ERR_BadAccess, "new Top<int>.Outer<string>()").WithArguments("Top<int>.Outer<string>")); } [WorkItem(528591, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528591")] [Fact] public void CS0121ERR_IncorrectErrorSpan1() { CreateCompilation(@" class Test { public static void Method1(int a, long b) { } public static void Method1(long a, int b) { } public static void Main() { Method1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Method1(int, long)' and 'Test.Method1(long, int)' // Method1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Method1").WithArguments("Test.Method1(int, long)", "Test.Method1(long, int)")); } [WorkItem(528592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528592")] [Fact] public void CS0121ERR_IncorrectErrorSpan2() { CreateCompilation(@" public class Class1 { public Class1(int a, long b) { } public Class1(long a, int b) { } } class Test { public static void Main() { var i1 = new Class1(10, 20); //CS0121 } } ").VerifyDiagnostics( // (17,18): error CS0121: The call is ambiguous between the following methods or properties: 'Class1.Class1(int, long)' and 'Class1.Class1(long, int)' // new Class1(10, 20) Diagnostic(ErrorCode.ERR_AmbigCall, "Class1").WithArguments("Class1.Class1(int, long)", "Class1.Class1(long, int)")); } [WorkItem(542468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542468")] [Fact] public void CS1513ERR_RbraceExpected_DevDiv9741() { var text = @" class Program { private delegate string D(); static void Main(string[] args) { D d = delegate { .ToString(); }; } } "; // Used to assert. CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 10), // (9,14): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // .ToString(); Diagnostic(ErrorCode.ERR_ObjectRequired, "ToString").WithArguments("object.ToString()").WithLocation(9, 14), // (7,15): error CS1643: Not all code paths return a value in anonymous method of type 'Program.D' // D d = delegate Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "Program.D").WithLocation(7, 15) ); } [WorkItem(543473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543473")] [Fact] public void CS0815ERR_CannotAssignLambdaExpressionToAnImplicitlyTypedLocalVariable() { var text = @"class Program { static void Main(string[] args) { var a1 = checked((a) => a); } }"; CreateCompilation(text).VerifyDiagnostics( // (5,26): error CS8917: The delegate type could not be inferred. // var a1 = checked((a) => a); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "(a) => a").WithLocation(5, 26)); } [Fact, WorkItem(543665, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543665")] public void CS0246ERR_SingleTypeNameNotFound_UndefinedTypeInDelegateSignature() { var text = @" using System; class Test { static void Main() { var d = (Action<List<int>>)delegate(List<int> t) {}; } }"; CreateCompilation(text).VerifyDiagnostics( // (7,41): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 41), // (7,21): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // var d = (Action<List<int>>)delegate(List<int> t) {}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(7, 21) ); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_StaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(633183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633183")] public void CS0199ERR_RefReadonlyStatic_NestedStaticFieldInitializer() { var source = @" class Program { Program(ref string s) { } static readonly Program Field1 = new Program(ref Program.Field2); static readonly string Field2 = """"; static void Main() { } class Inner { static readonly Program Field3 = new Program(ref Program.Field2); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,58): error CS0199: A static readonly field cannot be used as a ref or out value (except in a static constructor) // static readonly Program Field3 = new Program(ref Program.Field2); Diagnostic(ErrorCode.ERR_RefReadonlyStatic, "Program.Field2").WithLocation(11, 58) ); } [Fact] public void BadYield_MultipleReasons() { var source = @" using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { try { yield return 11; // CS1626 } catch { yield return 12; // CS1626 } finally { yield return 13; // CS1625 } } catch { try { yield return 21; // CS1626 } catch { yield return 22; // CS1631 } finally { yield return 23; // CS1625 } } finally { try { yield return 31; // CS1625 } catch { yield return 32; // CS1625 } finally { yield return 33; // CS1625 } } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 11; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (16,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 12; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (20,17): error CS1625: Cannot yield in the body of a finally clause // yield return 13; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (27,17): error CS1626: Cannot yield a value in the body of a try block with a catch clause // yield return 21; // CS1626 Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield"), // (31,17): error CS1631: Cannot yield a value in the body of a catch clause // yield return 22; // CS1631 Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield"), // (35,17): error CS1625: Cannot yield in the body of a finally clause // yield return 23; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (42,17): error CS1625: Cannot yield in the body of a finally clause // yield return 31; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (46,17): error CS1625: Cannot yield in the body of a finally clause // yield return 32; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (50,17): error CS1625: Cannot yield in the body of a finally clause // yield return 33; // CS1625 Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield")); } [Fact] public void BadYield_Lambda() { var source = @" using System; using System.Collections.Generic; class Program { IEnumerable<int> Test() { try { } finally { Action a = () => { yield break; }; Action b = () => { try { } finally { yield break; } }; } yield break; } } "; CreateCompilation(source).VerifyDiagnostics( // (14,32): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // Action a = () => { yield break; }; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield"), // CONSIDER: ERR_BadYieldInFinally is redundant, but matches dev11. // (22,21): error CS1625: Cannot yield in the body of a finally clause // yield break; Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield"), // (22,21): error CS1621: The yield statement cannot be used inside an anonymous method or lambda expression // yield break; Diagnostic(ErrorCode.ERR_YieldInAnonMeth, "yield")); } #endregion [Fact] public void Bug528147() { var text = @" using System; interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void Main() { D d = M; d(null); } } "; CreateCompilation(text).VerifyDiagnostics( // (25,15): error CS0122: 'Program.M<A.B>(I<A.B>)' is inaccessible due to its protection level // D d = M; Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("Program.M<A.B>(I<A.B>)") ); } [WorkItem(630799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/630799")] [Fact] public void Bug630799() { var text = @" using System; class Program { static void Goo<T,S>() where T : S where S : Exception { try { } catch(S e) { } catch(T e) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (14,15): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('S') // catch(T e) Diagnostic(ErrorCode.ERR_UnreachableCatch, "T").WithArguments("S").WithLocation(14, 15), // (11,17): warning CS0168: The variable 'e' is declared but never used // catch(S e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(11, 17), // (14,17): warning CS0168: The variable 'e' is declared but never used // catch(T e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(14, 17) ); } [Fact] public void ConditionalMemberAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { } static void Main(string[] args) { var x = 123 ?.ToString(); var p = new Program(); var x1 = p.P1 ?.ToString(); var x2 = p.V() ?.ToString(); var x3 = p.V ?.ToString(); var x4 = ()=> { return 1; } ?.ToString(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (13,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(13, 21), // (16,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?.ToString(); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(16, 18), // (17,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(17, 24), // (18,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?.ToString(); Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(18, 20), // (19,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = ()=> { return 1; } ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "()=> { return 1; } ?.ToString()").WithArguments("?", "lambda expression").WithLocation(19, 18) ); } [Fact] public void ConditionalMemberAccess002_notIn5() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (14,18): error CS8026: Feature 'null propagation operator' is not available in C# 5. Please use language version 6 or greater. // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "p.P1 ?.ToString").WithArguments("null propagating operator", "6").WithLocation(14, 18), // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] public void ConditionalMemberAccess002() { var text = @" class Program { public int? P1 { get { return null; } } public void V() { } static void Main(string[] args) { var p = new Program(); var x1 = p.P1 ?.ToString; } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (14,23): error CS0023: Operator '?' cannot be applied to operand of type 'method group' // var x1 = p.P1 ?.ToString; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "method group").WithLocation(14, 23) ); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(23009, "https://github.com/dotnet/roslyn/issues/23009")] public void ConditionalElementAccess001() { var text = @" class Program { public int P1 { set { } } public void V() { var x6 = base?.ToString(); } static void Main(string[] args) { var x = 123 ?[1,2]; var p = new Program(); var x1 = p.P1 ?[1,2]; var x2 = p.V() ?[1,2]; var x3 = p.V ?[1,2]; var x4 = ()=> { return 1; } ?[1,2]; var x5 = null?.ToString(); } } "; var compilation = CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,18): error CS0175: Use of keyword 'base' is not valid in this context // var x6 = base?.ToString(); Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(11, 18), // (16,21): error CS0023: Operator '?' cannot be applied to operand of type 'int' // var x = 123 ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "int").WithLocation(16, 21), // (19,18): error CS0154: The property or indexer 'Program.P1' cannot be used in this context because it lacks the get accessor // var x1 = p.P1 ?[1,2]; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "p.P1").WithArguments("Program.P1").WithLocation(19, 18), // (20,24): error CS0023: Operator '?' cannot be applied to operand of type 'void' // var x2 = p.V() ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void").WithLocation(20, 24), // (21,20): error CS0119: 'Program.V()' is a method, which is not valid in the given context // var x3 = p.V ?[1,2]; Diagnostic(ErrorCode.ERR_BadSKunknown, "V").WithArguments("Program.V()", "method").WithLocation(21, 20), // (22,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = ()=> { return 1; } ?[1,2]; Diagnostic(ErrorCode.ERR_BadUnaryOp, "()=> { return 1; } ?[1,2]").WithArguments("?", "lambda expression").WithLocation(22, 18), // (24,22): error CS0023: Operator '?' cannot be applied to operand of type '<null>' // var x5 = null?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "<null>").WithLocation(24, 22) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().First(); Assert.Equal("base?.ToString()", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IConditionalAccessOperation (OperationKind.ConditionalAccess, Type: ?, IsInvalid) (Syntax: 'base?.ToString()') Operation: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base') WhenNotNull: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IConditionalAccessInstanceOperation (OperationKind.ConditionalAccessInstance, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base') Arguments(0) "); } [Fact] [WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")] public void ConditionalMemberAccessPtr() { var text = @" using System; class Program { unsafe static void Main() { IntPtr? intPtr = null; var p = intPtr?.ToPointer(); } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,23): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // var p = intPtr?.ToPointer(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(9, 23) ); } [Fact] [WorkItem(991490, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991490")] public void ConditionalMemberAccessExprLambda() { var text = @" using System; using System.Linq.Expressions; class Program { static void M<T>(T x) { Expression<Func<string>> s = () => x?.ToString(); Expression<Func<char?>> c = () => x.ToString()?[0]; Expression<Func<int?>> c1 = () => x.ToString()?.Length; Expression<Func<int?>> c2 = () => x?.ToString()?.Length; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (9,44): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<string>> s = () => x?.ToString(); Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()").WithLocation(9, 44), // (10,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<char?>> c = () => x.ToString()?[0]; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?[0]").WithLocation(10, 43), // (11,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c1 = () => x.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x.ToString()?.Length").WithLocation(11, 43), // (13,43): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, "x?.ToString()?.Length").WithLocation(13, 43), // (13,45): error CS8072: An expression tree lambda may not contain a null propagating operator. // Expression<Func<int?>> c2 = () => x?.ToString()?.Length; Diagnostic(ErrorCode.ERR_NullPropagatingOpInExpressionTree, ".ToString()?.Length").WithLocation(13, 45) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda() { var text = @" using System; using System.Linq.Expressions; using System.Collections.Generic; class Program { static void M<T>(T x) { Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; } static void Main() { M((string)null); } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (10,87): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<Dictionary<int, int>>> s = () => new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, "[1]").WithLocation(10, 87) ); } [Fact] [WorkItem(915609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/915609")] public void DictionaryInitializerInExprLambda1() { var text = @" using System; using System.Collections.Generic; using System.Linq.Expressions; namespace ConsoleApplication31 { class Program { static void Main(string[] args) { var o = new Goo(); var x = o.E.Compile()().Pop(); System.Console.WriteLine(x); } } static class StackExtensions { public static void Add<T>(this Stack<T> s, T x) => s.Push(x); } class Goo { public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; } } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (25,72): error CS8075: An expression tree lambda may not contain an extension collection element initializer. // public Expression<Func<Stack<int>>> E = () => new Stack<int> { 42 }; Diagnostic(ErrorCode.ERR_ExtensionCollectionElementInitializerInExpressionTree, "42").WithLocation(25, 72) ); } [WorkItem(310, "https://github.com/dotnet/roslyn/issues/310")] [Fact] public void ExtensionElementInitializerInExpressionLambda() { var text = @" using System; using System.Collections; using System.Linq.Expressions; class C { static void Main() { Expression<Func<C>> e = () => new C { H = { [""Key""] = ""Value"" } }; Console.WriteLine(e); var c = e.Compile().Invoke(); Console.WriteLine(c.H[""Key""]); } readonly Hashtable H = new Hashtable(); } "; CreateCompilationWithMscorlib45(text, new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }).VerifyDiagnostics( // (9,53): error CS8073: An expression tree lambda may not contain a dictionary initializer. // Expression<Func<C>> e = () => new C { H = { ["Key"] = "Value" } }; Diagnostic(ErrorCode.ERR_DictionaryInitializerInExpressionTree, @"[""Key""]").WithLocation(9, 53) ); } [WorkItem(12900, "https://github.com/dotnet/roslyn/issues/12900")] [WorkItem(17138, "https://github.com/dotnet/roslyn/issues/17138")] [Fact] public void CSharp7FeaturesInExprTrees() { var source = @" using System; //using System.Collections; using System.Linq.Expressions; class C { static void Main() { // out variable declarations Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 // pattern matching object o = 3; Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 // direct tuple creation could be OK, as it is just a constructor invocation, // not for long tuples the generated code is more complex, and we would // prefer custom expression trees to express the semantics. Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal // tuple conversions (byte, byte) t1 = (1, 2); Expression<Func<(byte a, byte b)>> e5 = () => t1; // OK, identity conversion Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method // discard Expression<Func<bool>> e8 = () => TryGetThree(out int _); Expression<Func<bool>> e9 = () => TryGetThree(out var _); Expression<Func<bool>> e10 = () => _ = (bool)o; Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Expression<Func<bool>> e14 = () => TryGetThree(out _); } static bool TryGetThree(out int three) { three = 3; return true; } static int three = 3; static ref int GetRefThree() { return ref three; } static int TakeRef(ref int x) { Console.WriteLine(""wow""); return x; } static (object, object) GetTuple() { return (null, null); } } namespace System { struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref=""System.ValueTuple""/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct )] public sealed class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] transformNames) { } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (34,50): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e12 = () => _ = var (a, _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a, _)").WithLocation(34, 50), // (35,51): error CS8185: A declaration is not allowed in this context. // Expression<Func<object>> e13 = () => _ = (var a, var _) = GetTuple(); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var a").WithLocation(35, 51), // (10,59): error CS8198: An expression tree may not contain an out argument variable declaration. // Expression<Func<bool>> e1 = () => TryGetThree(out int x) && x == 3; // ERROR 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x").WithLocation(10, 59), // (14,43): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<bool>> e2 = () => o is int y && y == 3; // ERROR 2 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "o is int y").WithLocation(14, 43), // (19,45): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e3 = () => (1, o); // ERROR 3: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, o)").WithLocation(19, 45), // (20,49): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<(int, int)>> e4 = () => (1, 2); // ERROR 4: tuple literal Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(1, 2)").WithLocation(20, 49), // (25,49): error CS8144: An expression tree may not contain a tuple conversion. // Expression<Func<(int, int)>> e6 = () => t1; // ERROR 5: tuple conversion Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleConversion, "t1").WithLocation(25, 49), // (27,54): error CS8156: An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference // Expression<Func<int>> e7 = () => TakeRef(ref GetRefThree()); // ERROR 6: calling ref-returning method Diagnostic(ErrorCode.ERR_RefReturningCallInExpressionTree, "GetRefThree()").WithLocation(27, 54), // (30,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e8 = () => TryGetThree(out int _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "int _").WithLocation(30, 59), // (31,59): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e9 = () => TryGetThree(out var _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "var _").WithLocation(31, 59), // (32,44): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<bool>> e10 = () => _ = (bool)o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (bool)o").WithLocation(32, 44), // (33,46): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "_ = (_, _) = GetTuple()").WithLocation(33, 46), // (33,50): error CS8143: An expression tree may not contain a tuple literal. // Expression<Func<object>> e11 = () => _ = (_, _) = GetTuple(); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsTupleLiteral, "(_, _)").WithLocation(33, 50), // (36,60): error CS8205: An expression tree may not contain a discard. // Expression<Func<bool>> e14 = () => TryGetThree(out _); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsDiscard, "_").WithLocation(36, 60) ); } [Fact] public void DictionaryInitializerInCS5() { var text = @" using System.Collections.Generic; class Program { static void Main() { var s = new Dictionary<int, int> () {[1] = 2}; } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)).VerifyDiagnostics( // (8,46): error CS8026: Feature 'dictionary initializer' is not available in C# 5. Please use language version 6 or greater. // var s = new Dictionary<int, int> () {[1] = 2}; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "[1] = 2").WithArguments("dictionary initializer", "6").WithLocation(8, 46) ); } [Fact] public void DictionaryInitializerDataFlow() { var text = @" using System.Collections.Generic; class Program { static void Main() { int i; var s = new Dictionary<int, int> () {[i] = 2}; i = 1; System.Console.WriteLine(i); } static void Goo() { int i; var s = new Dictionary<int, int> () {[i = 1] = 2}; System.Console.WriteLine(i); } } "; CreateCompilationWithMscorlib45(text, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (9,47): error CS0165: Use of unassigned local variable 'i' // var s = new Dictionary<int, int> () {[i] = 2}; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(9, 47) ); } [Fact] public void ConditionalMemberAccessNotStatement() { var text = @" class Program { static void Main() { var x = new int[10]; x?.Length; x?[1]; x?.ToString()[1]; } } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.Length; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.Length").WithLocation(8, 9), // (9,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?[1]").WithLocation(9, 9), // (10,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x?.ToString()[1]; Diagnostic(ErrorCode.ERR_IllegalStatement, "x?.ToString()[1]").WithLocation(10, 9) ); } [WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")] [Fact] public void ConditionalMemberAccessRefLike() { var text = @" class Program { static void Main(string[] args) { var o = new Program(); o?.F(); // this is ok var x = o?.F(); var y = o?.F() ?? default; var z = o?.F().field ?? default; } S2 F() => throw null; } public ref struct S1 { } public ref struct S2 { public S1 field; } "; CreateCompilationWithMscorlib45(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (10,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var x = o?.F(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(10, 18), // (12,18): error CS0023: Operator '?' cannot be applied to operand of type 'S2' // var y = o?.F() ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S2").WithLocation(12, 18), // (14,18): error CS0023: Operator '?' cannot be applied to operand of type 'S1' // var z = o?.F().field ?? default; Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "S1").WithLocation(14, 18) ); } [Fact] [WorkItem(1179322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179322")] public void LabelSameNameAsParameter() { var text = @" class Program { static object M(object obj, object value) { if (((string)obj).Length == 0) value: new Program(); } } "; var compilation = CreateCompilation(text); compilation.GetParseDiagnostics().Verify(); // Make sure the compiler can handle producing method body diagnostics for this pattern when // queried via an API (command line compile would exit after parse errors were reported). compilation.GetMethodBodyDiagnostics().Verify( // (6,41): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "value: new Program();").WithLocation(6, 41), // (6,41): warning CS0164: This label has not been referenced // if (((string)obj).Length == 0) value: new Program(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "value").WithLocation(6, 41), // (4,19): error CS0161: 'Program.M(object, object)': not all code paths return a value // static object M(object obj, object value) Diagnostic(ErrorCode.ERR_ReturnExpected, "M").WithArguments("Program.M(object, object)").WithLocation(4, 19)); } [Fact] public void ThrowInExpressionTree() { var text = @" using System; using System.Linq.Expressions; namespace ConsoleApplication1 { class Program { static bool b = true; static object o = string.Empty; static void Main(string[] args) { Expression<Func<object>> e1 = () => o ?? throw null; Expression<Func<object>> e2 = () => b ? throw null : o; Expression<Func<object>> e3 = () => b ? o : throw null; Expression<Func<object>> e4 = () => throw null; } } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (13,54): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e1 = () => o ?? throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(13, 54), // (14,53): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e2 = () => b ? throw null : o; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(14, 53), // (15,57): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e3 = () => b ? o : throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(15, 57), // (16,49): error CS8188: An expression tree may not contain a throw-expression. // Expression<Func<object>> e4 = () => throw null; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsThrowExpression, "throw null").WithLocation(16, 49) ); } [Fact, WorkItem(17674, "https://github.com/dotnet/roslyn/issues/17674")] public void VoidDiscardAssignment() { var text = @" class Program { public static void Main(string[] args) { _ = M(); } static void M() { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M(); Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9) ); } [Fact, WorkItem(22880, "https://github.com/dotnet/roslyn/issues/22880")] public void AttributeCtorInParam() { var text = @" [A(1)] class A : System.Attribute { A(in int x) { } } [B()] class B : System.Attribute { B(in int x = 1) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (2,2): error CS8358: Cannot use attribute constructor 'A.A(in int)' because it has 'in' parameters. // [A(1)] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "A(1)").WithArguments("A.A(in int)").WithLocation(2, 2), // (7,2): error CS8358: Cannot use attribute constructor 'B.B(in int)' because it has 'in' parameters. // [B()] Diagnostic(ErrorCode.ERR_AttributeCtorInParameter, "B()").WithArguments("B.B(in int)").WithLocation(7, 2) ); } [Fact] public void ERR_ExpressionTreeContainsSwitchExpression() { var text = @" using System; using System.Linq.Expressions; public class C { public int Test() { Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 return 1; } }"; CreateCompilationWithMscorlib40AndSystemCore(text, parseOptions: TestOptions.RegularWithRecursivePatterns).VerifyDiagnostics( // (9,45): error CS8411: An expression tree may not contain a switch expression. // Expression<Func<int, int>> e = a => a switch { 0 => 1, _ => 2 }; // CS8411 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsSwitchExpression, "a switch { 0 => 1, _ => 2 }").WithLocation(9, 45) ); } [Fact] public void PointerGenericConstraintTypes() { var source = @" namespace A { class D {} } class B {} unsafe class C<T, U, V, X, Y, Z> where T : byte* where U : unmanaged where V : U* where X : object* where Y : B* where Z : A.D* { void M1<A>() where A : byte* {} void M2<A, B>() where A : unmanaged where B : A* {} void M3<A>() where A : object* {} void M4<A>() where A : B* {} void M5<A>() where A : T {} }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); comp.VerifyDiagnostics( // (9,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // unsafe class C<T, U, V, X, Y, Z> where T : byte* Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(9, 44), // (11,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where V : U* Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(11, 44), // (12,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where X : object* Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(12, 44), // (13,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Y : B* Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(13, 44), // (14,44): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where Z : A.D* Diagnostic(ErrorCode.ERR_BadConstraintType, "A.D*").WithLocation(14, 44), // (16,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M1<A>() where A : byte* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "byte*").WithLocation(16, 28), // (18,31): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // where B : A* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "A*").WithLocation(18, 31), // (19,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M3<A>() where A : object* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object*").WithLocation(19, 28), // (20,28): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M4<A>() where A : B* {} Diagnostic(ErrorCode.ERR_BadConstraintType, "B*").WithLocation(20, 28) ); } [Fact] public void ArrayGenericConstraintTypes() { var source = @"class A<T> where T : object[] {}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,22): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // class A<T> where T : object[] {} Diagnostic(ErrorCode.ERR_BadConstraintType, "object[]").WithLocation(1, 22)); } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class EditAndContinuePdbTests : EditAndContinueTestBase { [Theory] [MemberData(nameof(ExternalPdbFormats))] public void MethodExtents(DebugInformationFormat format) { var source0 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""1111111111111111111111111111111111111111"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 20 ""C:\F\B.cs"" Console.WriteLine(); #line default } int E() => 1; void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; }</N:1>; } } "), fileName: @"C:\Enc1.cs"); var source1 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""2222222222222222222222222222222222222222"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 10 ""C:\F\C.cs"" Console.WriteLine(); #line default } void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; } "), fileName: @"C:\Enc1.cs"); var source2 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""3333333333333333333333333333333333333333"" using System; public class C { int A() => 3; void F() { #line 10 ""C:\F\B.cs"" Console.WriteLine(); #line 10 ""C:\F\E.cs"" Console.WriteLine(); #line default } void G() { Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; int B() => 4; } "), fileName: @"C:\Enc1.cs"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "EncMethodExtents"); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); compilation0.VerifyDiagnostics(); compilation1.VerifyDiagnostics(); compilation2.VerifyDiagnostics(); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var a1 = compilation1.GetMember<MethodSymbol>("C.A"); var a2 = compilation2.GetMember<MethodSymbol>("C.A"); var b2 = compilation2.GetMember<MethodSymbol>("C.B"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, syntaxMap1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, syntaxMap1, preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, <G>b__3_0, <G>b__3_1, <G>b__3_2, <G>b__3_3#1}"); var reader1 = diff1.GetMetadata().Reader; CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(5, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(8, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(10, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation)); } diff1.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""0B-95-CB-78-00-AE-C7-34-45-D9-FB-31-E4-30-A4-0E-FC-EA-9E-95"" /> <file id=""2"" name=""C:\F\A.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\C.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""54"" document=""1"" /> <entry offset=""0x21"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x41"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H1"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x6000008""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""46"" endLine=""19"" endColumn=""47"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H3"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x600000a""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""50"" endLine=""23"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g1, g2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, a1, a2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Insert, null, b2))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_3#1, <>9__3_1, <G>b__3_1, <G>b__3_3#1, <>9__3_0, <>9__3_2, <G>b__3_0, <G>b__3_2}"); var reader2 = diff2.GetMetadata().Reader; CheckEncLogDefinitions(reader2, Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(1, TableIndex.MethodDebugInformation), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation), Handle(12, TableIndex.MethodDebugInformation)); } diff2.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""9C-B9-FF-18-0E-9F-A4-22-93-85-A8-5A-06-11-43-1E-64-3E-88-06"" /> <file id=""2"" name=""C:\F\B.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\E.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""16"" endLine=""6"" endColumn=""17"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000002""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x21"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000c""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""30"" startColumn=""16"" endLine=""30"" endColumn=""17"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class EditAndContinuePdbTests : EditAndContinueTestBase { [Theory] [MemberData(nameof(ExternalPdbFormats))] public void MethodExtents(DebugInformationFormat format) { var source0 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""1111111111111111111111111111111111111111"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 20 ""C:\F\B.cs"" Console.WriteLine(); #line default } int E() => 1; void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; }</N:1>; } } "), fileName: @"C:\Enc1.cs"); var source1 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""2222222222222222222222222222222222222222"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 10 ""C:\F\C.cs"" Console.WriteLine(); #line default } void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; } "), fileName: @"C:\Enc1.cs"); var source2 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""3333333333333333333333333333333333333333"" using System; public class C { int A() => 3; void F() { #line 10 ""C:\F\B.cs"" Console.WriteLine(); #line 10 ""C:\F\E.cs"" Console.WriteLine(); #line default } void G() { Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; int B() => 4; } "), fileName: @"C:\Enc1.cs"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "EncMethodExtents"); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); compilation0.VerifyDiagnostics(); compilation1.VerifyDiagnostics(); compilation2.VerifyDiagnostics(); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var a1 = compilation1.GetMember<MethodSymbol>("C.A"); var a2 = compilation2.GetMember<MethodSymbol>("C.A"); var b2 = compilation2.GetMember<MethodSymbol>("C.B"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, syntaxMap1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, syntaxMap1, preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, <G>b__3_0, <G>b__3_1, <G>b__3_2, <G>b__3_3#1}"); var reader1 = diff1.GetMetadata().Reader; CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(5, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(8, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(10, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation)); } diff1.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""0B-95-CB-78-00-AE-C7-34-45-D9-FB-31-E4-30-A4-0E-FC-EA-9E-95"" /> <file id=""2"" name=""C:\F\A.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\C.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""54"" document=""1"" /> <entry offset=""0x21"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x41"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H1"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x6000008""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""46"" endLine=""19"" endColumn=""47"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H3"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x600000a""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""50"" endLine=""23"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g1, g2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, a1, a2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Insert, null, b2))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_3#1, <>9__3_1, <G>b__3_1, <G>b__3_3#1, <>9__3_0, <>9__3_2, <G>b__3_0, <G>b__3_2}"); var reader2 = diff2.GetMetadata().Reader; CheckEncLogDefinitions(reader2, Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(1, TableIndex.MethodDebugInformation), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation), Handle(12, TableIndex.MethodDebugInformation)); } diff2.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""9C-B9-FF-18-0E-9F-A4-22-93-85-A8-5A-06-11-43-1E-64-3E-88-06"" /> <file id=""2"" name=""C:\F\B.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\E.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""16"" endLine=""6"" endColumn=""17"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000002""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x21"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000c""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""30"" startColumn=""16"" endLine=""30"" endColumn=""17"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Quite este valor cuando se agregue otro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Quite este valor cuando se agregue otro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Dependencies/Collections/Internal/ICollectionCalls`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections.Internal { /// <summary> /// Provides static methods to invoke <see cref="ICollection{T}"/> members on value types that explicitly implement /// the member. /// </summary> /// <remarks> /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a /// normal call to an implicitly implemented member. /// </remarks> internal static class ICollectionCalls<T> { public static bool IsReadOnly<TCollection>(ref TCollection collection) where TCollection : ICollection<T> => collection.IsReadOnly; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections.Internal { /// <summary> /// Provides static methods to invoke <see cref="ICollection{T}"/> members on value types that explicitly implement /// the member. /// </summary> /// <remarks> /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a /// normal call to an implicitly implemented member. /// </remarks> internal static class ICollectionCalls<T> { public static bool IsReadOnly<TCollection>(ref TCollection collection) where TCollection : ICollection<T> => collection.IsReadOnly; } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./eng/prepare-tests.ps1
[CmdletBinding(PositionalBinding=$false)] param ([string]$configuration = "Debug") Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" try { . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot $dotnet = Ensure-DotnetSdk # permissions issues make this a pain to do in PrepareTests itself. Remove-Item -Recurse -Force "$RepoRoot\artifacts\testPayload" -ErrorAction SilentlyContinue Exec-Console $dotnet "$RepoRoot\artifacts\bin\PrepareTests\$configuration\net5.0\PrepareTests.dll --source $RepoRoot --destination $RepoRoot\artifacts\testPayload" exit 0 } catch { Write-Host $_ exit 1 } finally { Pop-Location }
[CmdletBinding(PositionalBinding=$false)] param ([string]$configuration = "Debug") Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" try { . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot $dotnet = Ensure-DotnetSdk # permissions issues make this a pain to do in PrepareTests itself. Remove-Item -Recurse -Force "$RepoRoot\artifacts\testPayload" -ErrorAction SilentlyContinue Exec-Console $dotnet "$RepoRoot\artifacts\bin\PrepareTests\$configuration\net5.0\PrepareTests.dll --source $RepoRoot --destination $RepoRoot\artifacts\testPayload" exit 0 } catch { Write-Host $_ exit 1 } finally { Pop-Location }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/EditorFeatures/Test2/Rename/InlineRenameTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class InlineRenameTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> object [|$$test|] = new object(); var other = [|test|]; </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "renamed") session.Commit() Await VerifyTagsAreCorrect(workspace, "renamedtest") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { C _ = null; System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; }; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(46208, "https://github.com/dotnet/roslyn/issues/46208")> Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Test1$$|] { } ]]></Document> </Project> </Workspace>, host) Dim options = workspace.CurrentSolution.Options workspace.TryApplyChanges( workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True))) Dim session = StartSession(workspace) Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") session.Commit() Await VerifyTagsAreCorrect(workspace, "Test1<>") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")> Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> [|$$x|]) { foreach (var (y1, y2) in [|x|]) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } var (z1, z2) = this; [|Deconstruct|](out var t1, out var t2); } void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")> Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace, originalTextToRename As String, renameTextPrefix As String, Optional renameOverloads As Boolean = False, Optional renameInStrings As Boolean = False, Optional renameInComments As Boolean = False, Optional renameFile As Boolean = False, Optional fileToRename As DocumentId = Nothing) As Task Dim optionSet = workspace.Options optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim session = StartSession(workspace) ' Type a bit in the file Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix) Dim replacementText = renameTextPrefix + originalTextToRename Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, replacementText) session.Commit() Await VerifyTagsAreCorrect(workspace, replacementText) If renameFile Then If fileToRename Is Nothing Then VerifyFileName(workspace, replacementText) Else VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText) End If End If End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public void [|$$goo|]() { [|goo|](); } public void [|goo|]&lt;T&gt;() { [|goo|]&lt;T&gt;(); } public void [|goo|](int i) { [|goo|](i); } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Imports System.Linq Imports System Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$goo|]() [|goo|]() End Sub Public Sub [|goo|](of T)() [|goo|](of T)() End Sub Public Sub [|goo|](s As String) [|goo|](s) End Sub Public Shared Sub [|goo|](d As Double) [|goo|](d) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")> Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Program Sub Main([|$$args|] As String()) End Sub End Class </Document> <Document> ' args </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) ' https://github.com/dotnet/roslyn/issues/36075 ' VerifyFileRename(workspace, "ABC") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class [|$$C|] { } // [|C|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|C|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { private void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // F ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { public void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // [|F|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")> Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"><![CDATA[ public class [|$$C|] { } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB") Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void [|goo|](int i) { [|goo|](i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "[|goo|]"; var b = $"{1}[|goo|]{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub [|goo|](i As Integer) [|goo|](i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "[|goo|]" Dim b = $"{1}[|goo|]{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SimpleEditAndCancel(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim initialTextSnapshot = textBuffer.CurrentSnapshot textBuffer.Insert(caretPosition, "Bar") session.Cancel() ' Assert the file is what it started as Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText()) ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$dynamic|] { void M() { [|dynamic|] d; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "goo") session.Commit() Await VerifyTagsAreCorrect(workspace, "goodynamic") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReadOnlyRegionsCreated(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$C { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.False(buffer.IsReadOnly(cursorPosition)) Assert.False(buffer.IsReadOnly(cursorPosition + 1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) ' Make sure we can't type at the start or end Assert.True(buffer.IsReadOnly(0)) Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length)) session.Cancel() ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")> Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$C c; class C { }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Assert.False(buffer.IsReadOnly(0)) Assert.False(buffer.IsReadOnly(1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) session.Cancel() VerifyFileName(workspace, "Test1.cs") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class AAAA { public abstract void [|Goo|](); } class BBBB : AAAA { public override void [|Goo|]() { } } class DDDD : BBBB { public override void [|Goo|]() { } } class CCCC : AAAA { public override void [|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="GooBar") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarGoo") session.Cancel() Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") textBuffer.Insert(caretPosition, "Baz") Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1) End Using End Function <WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) ' Preview should not return null Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = False Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title) Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description) Assert.Equal("Goo", previewService.TopLevelName) Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = True Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) ' Session should still be up; type some more caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Insert(caretPosition, "Cat") previewService.ReturnsNull = False previewService.Called = False session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "CatBarGoo") Assert.True(previewService.Called) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Sub [|M$$|]() End Sub Sub Test() #If Proj1 Then [|M|]() #End If #If Proj2 Then [|M|]() #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "o") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mo") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mow") session.Commit() Await VerifyTagsAreCorrect(workspace, "Mow") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Dim [|m$$|] As Integer Sub Test() #If Proj1 Then Dim x = [|m|] #End If #If Proj2 Then Dim x = [|m|] #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "ma") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "maw") session.Commit() Await VerifyTagsAreCorrect(workspace, "maw") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")> Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { void M() { var z = {|introducelocal:5 + 5|}; var q = [|x$$|]; } int [|x|]; }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "yz") Await WaitForRename(workspace) ' Invoke a CodeAction Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider() Dim actions = New List(Of CodeAction) Dim context = New CodeRefactoringContext( workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(), Sub(a) actions.Add(a), CancellationToken.None) workspace.Documents.Single().AnnotatedSpans.Clear() introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService) Dim actualSeverity As NotificationSeverity = Nothing Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity editHandler.Apply( workspace, workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None), "unused", New ProgressTracker(), CancellationToken.None) ' CodeAction should be rejected Assert.Equal(NotificationSeverity.Error, actualSeverity) Assert.Equal(" class C { void M() { var z = 5 + 5; var q = xyz; } int xyz; }", textBuffer.CurrentSnapshot.GetText()) ' Rename should still be active Await VerifyTagsAreCorrect(workspace, "xyz") textBuffer.Insert(caretPosition + 2, "q") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "xyzq") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof([|M|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate starting a debugging session Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate ending break mode in the debugger (by stepping or continuing) Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")> Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task ' Everything on the last line of main is parsed as a single invocation expression ' with CType(...) as the receiver and everything else as arguments. ' Rename doesn't expect to see CType as the receiver of an invocation. Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3} Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)( CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing) End Sub End Module </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") session.Commit() Await VerifyTagsAreCorrect(workspace, "qp") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")> Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x; x = 2; void [|$$M|]() { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "x") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")> Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class1 Public Property [|$$Field1|] As Integer End Class Public Class Class2 Public Shared Property DataSource As IEnumerable(Of Class1) Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = ( From data In DataSource Group By data.Field1 Into Group1 = Group ).ToDictionary( Function(group) group.Field1, Function(group) group.Group1) End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "xield1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")> Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub New(a As Action) End Sub Public ReadOnly Property Vm As C Public ReadOnly Property Crash As New C(Sub() Vm.Sav() End Sub) Public Function Sav$$() As Boolean Return False End Function Public Function Save() As Boolean Return False End Function End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") session.Commit() End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Goo|] { void Blah() { } } </Document> <Document> partial class Goo { void BlahBlah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Test1|] { void Blah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { } } class Test2 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { } } class Test1 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$Test1|] { One, Two, Three } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|$$Test1|] { void Blah(); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyUnsupportedFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface Test1 { void [|$$Blah|](); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) ' Disable document changes to make sure file rename is not supported. ' Linked workspace files will report that applying changes to document ' info is not allowed; this is intended to mimic that behavior ' and make sure inline rename works as intended. workspace.CanApplyChangeDocument = False Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") session.Commit() VerifyFileName(workspace, "test1") End Using End Sub <WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) Assert.False(committed) Await VerifyTagsAreCorrect(workspace, "Test1") End Using End Function <WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test1 { void Blah() { [|$$Test2|] t2 = new [|Test2|](); } } </Document> <Document Name="Test2.cs"> class Test2 { } </Document> </Project> </Workspace>, host) Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs") Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")] class [|C|] { public [|$$C|]() { } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a); class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g = new [|Goo|](1); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class C { void M() { _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ; } public C [|$$Goo|] { get; set; } public C Other { get; set; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameInComment(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class [|$$MyClass|] { /// <summary> /// Initializes <see cref="MyClass"/>; /// </summary> MyClass() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True) session.Commit() Await VerifyTagsAreCorrect(workspace, "Example") End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class InlineRenameTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> object [|$$test|] = new object(); var other = [|test|]; </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "renamed") session.Commit() Await VerifyTagsAreCorrect(workspace, "renamedtest") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { C _ = null; System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; }; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(46208, "https://github.com/dotnet/roslyn/issues/46208")> Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Test1$$|] { } ]]></Document> </Project> </Workspace>, host) Dim options = workspace.CurrentSolution.Options workspace.TryApplyChanges( workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True))) Dim session = StartSession(workspace) Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") session.Commit() Await VerifyTagsAreCorrect(workspace, "Test1<>") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")> Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> [|$$x|]) { foreach (var (y1, y2) in [|x|]) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } var (z1, z2) = this; [|Deconstruct|](out var t1, out var t2); } void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")> Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace, originalTextToRename As String, renameTextPrefix As String, Optional renameOverloads As Boolean = False, Optional renameInStrings As Boolean = False, Optional renameInComments As Boolean = False, Optional renameFile As Boolean = False, Optional fileToRename As DocumentId = Nothing) As Task Dim optionSet = workspace.Options optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim session = StartSession(workspace) ' Type a bit in the file Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix) Dim replacementText = renameTextPrefix + originalTextToRename Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, replacementText) session.Commit() Await VerifyTagsAreCorrect(workspace, replacementText) If renameFile Then If fileToRename Is Nothing Then VerifyFileName(workspace, replacementText) Else VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText) End If End If End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public void [|$$goo|]() { [|goo|](); } public void [|goo|]&lt;T&gt;() { [|goo|]&lt;T&gt;(); } public void [|goo|](int i) { [|goo|](i); } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Imports System.Linq Imports System Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$goo|]() [|goo|]() End Sub Public Sub [|goo|](of T)() [|goo|](of T)() End Sub Public Sub [|goo|](s As String) [|goo|](s) End Sub Public Shared Sub [|goo|](d As Double) [|goo|](d) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")> Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Program Sub Main([|$$args|] As String()) End Sub End Class </Document> <Document> ' args </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) ' https://github.com/dotnet/roslyn/issues/36075 ' VerifyFileRename(workspace, "ABC") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class [|$$C|] { } // [|C|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|C|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { private void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // F ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { public void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // [|F|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")> Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"><![CDATA[ public class [|$$C|] { } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB") Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void [|goo|](int i) { [|goo|](i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "[|goo|]"; var b = $"{1}[|goo|]{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub [|goo|](i As Integer) [|goo|](i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "[|goo|]" Dim b = $"{1}[|goo|]{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SimpleEditAndCancel(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim initialTextSnapshot = textBuffer.CurrentSnapshot textBuffer.Insert(caretPosition, "Bar") session.Cancel() ' Assert the file is what it started as Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText()) ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$dynamic|] { void M() { [|dynamic|] d; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "goo") session.Commit() Await VerifyTagsAreCorrect(workspace, "goodynamic") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReadOnlyRegionsCreated(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$C { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.False(buffer.IsReadOnly(cursorPosition)) Assert.False(buffer.IsReadOnly(cursorPosition + 1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) ' Make sure we can't type at the start or end Assert.True(buffer.IsReadOnly(0)) Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length)) session.Cancel() ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")> Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$C c; class C { }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Assert.False(buffer.IsReadOnly(0)) Assert.False(buffer.IsReadOnly(1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) session.Cancel() VerifyFileName(workspace, "Test1.cs") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class AAAA { public abstract void [|Goo|](); } class BBBB : AAAA { public override void [|Goo|]() { } } class DDDD : BBBB { public override void [|Goo|]() { } } class CCCC : AAAA { public override void [|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="GooBar") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarGoo") session.Cancel() Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") textBuffer.Insert(caretPosition, "Baz") Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1) End Using End Function <WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) ' Preview should not return null Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = False Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title) Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description) Assert.Equal("Goo", previewService.TopLevelName) Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = True Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) ' Session should still be up; type some more caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Insert(caretPosition, "Cat") previewService.ReturnsNull = False previewService.Called = False session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "CatBarGoo") Assert.True(previewService.Called) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Sub [|M$$|]() End Sub Sub Test() #If Proj1 Then [|M|]() #End If #If Proj2 Then [|M|]() #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "o") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mo") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mow") session.Commit() Await VerifyTagsAreCorrect(workspace, "Mow") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Dim [|m$$|] As Integer Sub Test() #If Proj1 Then Dim x = [|m|] #End If #If Proj2 Then Dim x = [|m|] #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "ma") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "maw") session.Commit() Await VerifyTagsAreCorrect(workspace, "maw") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")> Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { void M() { var z = {|introducelocal:5 + 5|}; var q = [|x$$|]; } int [|x|]; }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "yz") Await WaitForRename(workspace) ' Invoke a CodeAction Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider() Dim actions = New List(Of CodeAction) Dim context = New CodeRefactoringContext( workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(), Sub(a) actions.Add(a), CancellationToken.None) workspace.Documents.Single().AnnotatedSpans.Clear() introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService) Dim actualSeverity As NotificationSeverity = Nothing Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity editHandler.Apply( workspace, workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None), "unused", New ProgressTracker(), CancellationToken.None) ' CodeAction should be rejected Assert.Equal(NotificationSeverity.Error, actualSeverity) Assert.Equal(" class C { void M() { var z = 5 + 5; var q = xyz; } int xyz; }", textBuffer.CurrentSnapshot.GetText()) ' Rename should still be active Await VerifyTagsAreCorrect(workspace, "xyz") textBuffer.Insert(caretPosition + 2, "q") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "xyzq") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof([|M|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate starting a debugging session Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate ending break mode in the debugger (by stepping or continuing) Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")> Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task ' Everything on the last line of main is parsed as a single invocation expression ' with CType(...) as the receiver and everything else as arguments. ' Rename doesn't expect to see CType as the receiver of an invocation. Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3} Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)( CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing) End Sub End Module </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") session.Commit() Await VerifyTagsAreCorrect(workspace, "qp") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")> Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x; x = 2; void [|$$M|]() { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "x") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")> Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class1 Public Property [|$$Field1|] As Integer End Class Public Class Class2 Public Shared Property DataSource As IEnumerable(Of Class1) Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = ( From data In DataSource Group By data.Field1 Into Group1 = Group ).ToDictionary( Function(group) group.Field1, Function(group) group.Group1) End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "xield1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")> Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub New(a As Action) End Sub Public ReadOnly Property Vm As C Public ReadOnly Property Crash As New C(Sub() Vm.Sav() End Sub) Public Function Sav$$() As Boolean Return False End Function Public Function Save() As Boolean Return False End Function End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") session.Commit() End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Goo|] { void Blah() { } } </Document> <Document> partial class Goo { void BlahBlah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Test1|] { void Blah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { } } class Test2 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { } } class Test1 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$Test1|] { One, Two, Three } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|$$Test1|] { void Blah(); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyUnsupportedFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface Test1 { void [|$$Blah|](); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) ' Disable document changes to make sure file rename is not supported. ' Linked workspace files will report that applying changes to document ' info is not allowed; this is intended to mimic that behavior ' and make sure inline rename works as intended. workspace.CanApplyChangeDocument = False Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") session.Commit() VerifyFileName(workspace, "test1") End Using End Sub <WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) Assert.False(committed) Await VerifyTagsAreCorrect(workspace, "Test1") End Using End Function <WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test1 { void Blah() { [|$$Test2|] t2 = new [|Test2|](); } } </Document> <Document Name="Test2.cs"> class Test2 { } </Document> </Project> </Workspace>, host) Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs") Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")] class [|C|] { public [|$$C|]() { } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a); class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g = new [|Goo|](1); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class C { void M() { _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ; } public C [|$$Goo|] { get; set; } public C Other { get; set; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameInComment(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class [|$$MyClass|] { /// <summary> /// Initializes <see cref="MyClass"/>; /// </summary> MyClass() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True) session.Commit() Await VerifyTagsAreCorrect(workspace, "Example") End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/VisualStudio/Core/Test/Progression/IsCalledByGraphQueryTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class IsCalledByGraphQueryTests <WpfFact> Public Async Function IsCalledBySimpleTests() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class A { public $$A() { } public virtual void Run() { } } class B : A { public B() { } override public void Run() { var x = new A(); x.Run(); } } class C { public C() { } public void Goo() { var x = new B(); x.Run(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsCalledByGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=A Member=.ctor)" Category="CodeSchema_Method" CodeSchemaProperty_IsConstructor="True" CodeSchemaProperty_IsPublic="True" CommonLabel="A" Icon="Microsoft.VisualStudio.Method.Public" Label="A"/> <Node Id="(@1 Type=B Member=Run)" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="Run" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="Run"/> </Nodes> <Links> <Link Source="(@1 Type=B Member=Run)" Target="(@1 Type=A Member=.ctor)" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class IsCalledByGraphQueryTests <WpfFact> Public Async Function IsCalledBySimpleTests() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> class A { public $$A() { } public virtual void Run() { } } class B : A { public B() { } override public void Run() { var x = new A(); x.Run(); } } class C { public C() { } public void Goo() { var x = new B(); x.Run(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsCalledByGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=A Member=.ctor)" Category="CodeSchema_Method" CodeSchemaProperty_IsConstructor="True" CodeSchemaProperty_IsPublic="True" CommonLabel="A" Icon="Microsoft.VisualStudio.Method.Public" Label="A"/> <Node Id="(@1 Type=B Member=Run)" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="Run" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="Run"/> </Nodes> <Links> <Link Source="(@1 Type=B Member=Run)" Target="(@1 Type=A Member=.ctor)" Category="CodeSchema_Calls"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Dependencies/Collections/Internal/xlf/Strings.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="../Strings.resx"> <body> <trans-unit id="Arg_ArrayPlusOffTooSmall"> <source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source> <target state="translated">대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요.</target> <note /> </trans-unit> <trans-unit id="Arg_BogusIComparer"> <source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source> <target state="translated">IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'.</target> <note /> </trans-unit> <trans-unit id="Arg_HTCapacityOverflow"> <source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source> <target state="translated">해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오.</target> <note /> </trans-unit> <trans-unit id="Arg_KeyNotFoundWithKey"> <source>The given key '{0}' was not present in the dictionary.</source> <target state="translated">지정된 키 '{0}'이(가) 사전에 없습니다.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanDestArray"> <source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source> <target state="translated">대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanSrcArray"> <source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source> <target state="translated">소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요.</target> <note /> </trans-unit> <trans-unit id="Arg_NonZeroLowerBound"> <source>The lower bound of target array must be zero.</source> <target state="translated">대상 배열의 하한은 0이어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Arg_RankMultiDimNotSupported"> <source>Only single dimensional arrays are supported for the requested action.</source> <target state="translated">요청한 동작에 대해 1차원 배열만 지원됩니다.</target> <note /> </trans-unit> <trans-unit id="Arg_WrongType"> <source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source> <target state="translated">"{0}" 값은 "{1}" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength"> <source>Object is not a array with the same number of elements as the array to compare it to.</source> <target state="translated">개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ArrayLB"> <source>Number was less than the array's lower bound in the first dimension.</source> <target state="translated">숫자가 첫째 차원에서 배열의 하한보다 작습니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_BiggerThanCollection"> <source>Larger than collection size.</source> <target state="translated">컬렉션 크기보다 큽니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Count"> <source>Count must be positive and count must refer to a location within the string/array/collection.</source> <target state="translated">개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Index"> <source>Index was out of range. Must be non-negative and less than the size of the collection.</source> <target state="translated">인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ListInsert"> <source>Index must be within the bounds of the List.</source> <target state="translated">인덱스는 목록의 범위 내에 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_NeedNonNegNum"> <source>Non-negative number required.</source> <target state="translated">음수가 아닌 수가 필요합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_SmallCapacity"> <source>capacity was less than the current size.</source> <target state="translated">용량이 현재 크기보다 작습니다.</target> <note /> </trans-unit> <trans-unit id="Argument_AddingDuplicateWithKey"> <source>An item with the same key has already been added. Key: {0}</source> <target state="translated">동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0}</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidArrayType"> <source>Target array type is not compatible with the type of items in the collection.</source> <target state="translated">대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다.</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidOffLen"> <source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source> <target state="translated">오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다.</target> <note /> </trans-unit> <trans-unit id="CannotFindOldValue"> <source>Cannot find the old value</source> <target state="new">Cannot find the old value</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported"> <source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source> <target state="translated">비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumFailedVersion"> <source>Collection was modified; enumeration operation may not execute.</source> <target state="translated">컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumOpCantHappen"> <source>Enumeration has either not started or has already finished.</source> <target state="translated">열거가 시작되지 않았거나 이미 완료되었습니다.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_IComparerFailed"> <source>Failed to compare two elements in the array.</source> <target state="translated">배열의 두 요소를 비교하지 못했습니다.</target> <note /> </trans-unit> <trans-unit id="NotSupported_FixedSizeCollection"> <source>Collection was of a fixed size.</source> <target state="translated">컬렉션이 고정 크기입니다.</target> <note /> </trans-unit> <trans-unit id="NotSupported_KeyCollectionSet"> <source>Mutating a key collection derived from a dictionary is not allowed.</source> <target state="translated">사전에서 파생된 키 컬렉션은 변경할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="NotSupported_ValueCollectionSet"> <source>Mutating a value collection derived from a dictionary is not allowed.</source> <target state="translated">사전에서 파생된 값 컬렉션은 변경할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Rank_MustMatch"> <source>The specified arrays must have the same number of dimensions.</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="../Strings.resx"> <body> <trans-unit id="Arg_ArrayPlusOffTooSmall"> <source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source> <target state="translated">대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요.</target> <note /> </trans-unit> <trans-unit id="Arg_BogusIComparer"> <source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source> <target state="translated">IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'.</target> <note /> </trans-unit> <trans-unit id="Arg_HTCapacityOverflow"> <source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source> <target state="translated">해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오.</target> <note /> </trans-unit> <trans-unit id="Arg_KeyNotFoundWithKey"> <source>The given key '{0}' was not present in the dictionary.</source> <target state="translated">지정된 키 '{0}'이(가) 사전에 없습니다.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanDestArray"> <source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source> <target state="translated">대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요.</target> <note /> </trans-unit> <trans-unit id="Arg_LongerThanSrcArray"> <source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source> <target state="translated">소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요.</target> <note /> </trans-unit> <trans-unit id="Arg_NonZeroLowerBound"> <source>The lower bound of target array must be zero.</source> <target state="translated">대상 배열의 하한은 0이어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Arg_RankMultiDimNotSupported"> <source>Only single dimensional arrays are supported for the requested action.</source> <target state="translated">요청한 동작에 대해 1차원 배열만 지원됩니다.</target> <note /> </trans-unit> <trans-unit id="Arg_WrongType"> <source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source> <target state="translated">"{0}" 값은 "{1}" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength"> <source>Object is not a array with the same number of elements as the array to compare it to.</source> <target state="translated">개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ArrayLB"> <source>Number was less than the array's lower bound in the first dimension.</source> <target state="translated">숫자가 첫째 차원에서 배열의 하한보다 작습니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_BiggerThanCollection"> <source>Larger than collection size.</source> <target state="translated">컬렉션 크기보다 큽니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Count"> <source>Count must be positive and count must refer to a location within the string/array/collection.</source> <target state="translated">개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_Index"> <source>Index was out of range. Must be non-negative and less than the size of the collection.</source> <target state="translated">인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_ListInsert"> <source>Index must be within the bounds of the List.</source> <target state="translated">인덱스는 목록의 범위 내에 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_NeedNonNegNum"> <source>Non-negative number required.</source> <target state="translated">음수가 아닌 수가 필요합니다.</target> <note /> </trans-unit> <trans-unit id="ArgumentOutOfRange_SmallCapacity"> <source>capacity was less than the current size.</source> <target state="translated">용량이 현재 크기보다 작습니다.</target> <note /> </trans-unit> <trans-unit id="Argument_AddingDuplicateWithKey"> <source>An item with the same key has already been added. Key: {0}</source> <target state="translated">동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0}</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidArrayType"> <source>Target array type is not compatible with the type of items in the collection.</source> <target state="translated">대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다.</target> <note /> </trans-unit> <trans-unit id="Argument_InvalidOffLen"> <source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source> <target state="translated">오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다.</target> <note /> </trans-unit> <trans-unit id="CannotFindOldValue"> <source>Cannot find the old value</source> <target state="new">Cannot find the old value</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported"> <source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source> <target state="translated">비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumFailedVersion"> <source>Collection was modified; enumeration operation may not execute.</source> <target state="translated">컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_EnumOpCantHappen"> <source>Enumeration has either not started or has already finished.</source> <target state="translated">열거가 시작되지 않았거나 이미 완료되었습니다.</target> <note /> </trans-unit> <trans-unit id="InvalidOperation_IComparerFailed"> <source>Failed to compare two elements in the array.</source> <target state="translated">배열의 두 요소를 비교하지 못했습니다.</target> <note /> </trans-unit> <trans-unit id="NotSupported_FixedSizeCollection"> <source>Collection was of a fixed size.</source> <target state="translated">컬렉션이 고정 크기입니다.</target> <note /> </trans-unit> <trans-unit id="NotSupported_KeyCollectionSet"> <source>Mutating a key collection derived from a dictionary is not allowed.</source> <target state="translated">사전에서 파생된 키 컬렉션은 변경할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="NotSupported_ValueCollectionSet"> <source>Mutating a value collection derived from a dictionary is not allowed.</source> <target state="translated">사전에서 파생된 값 컬렉션은 변경할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Rank_MustMatch"> <source>The specified arrays must have the same number of dimensions.</source> <target state="translated">지정한 배열의 차수가 같아야 합니다.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Tools/IdeCoreBenchmarks/FindReferencesBenchmarks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Storage; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FindReferencesBenchmarks { [Benchmark] public async Task RunFindReferences() { try { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var solutionPath = Path.Combine(roslynRoot, @"C:\github\roslyn\Compilers.sln"); if (!File.Exists(solutionPath)) throw new ArgumentException("Couldn't find Compilers.sln"); Console.Write("Found Compilers.sln: " + Process.GetCurrentProcess().Id); var assemblies = MSBuildMefHostServices.DefaultAssemblies .Add(typeof(AnalyzerRunnerHelper).Assembly) .Add(typeof(FindReferencesBenchmarks).Assembly); var services = MefHostServices.Create(assemblies); var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "9.0" }, }, services); if (workspace == null) throw new ArgumentException("Couldn't create workspace"); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite))); Console.WriteLine("Opening roslyn. Attach to: " + Process.GetCurrentProcess().Id); var start = DateTime.Now; var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result; Console.WriteLine("Finished opening roslyn: " + (DateTime.Now - start)); // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we // perform, including seeing how big the initial string table is. var storageService = workspace.Services.GetService<IPersistentStorageService>(); if (storageService == null) throw new ArgumentException("Couldn't get storage service"); using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None)) { Console.WriteLine(); } // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the // same. var project = solution.Projects.First(p => p.AssemblyName == "Microsoft.CodeAnalysis"); start = DateTime.Now; var compilation = await project.GetCompilationAsync(); Console.WriteLine("Time to get first compilation: " + (DateTime.Now - start)); var type = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.SyntaxToken"); if (type == null) throw new Exception("Couldn't find type"); Console.WriteLine("Starting find-refs"); start = DateTime.Now; var references = await SymbolFinder.FindReferencesAsync(type, solution); Console.WriteLine("Time to find-refs: " + (DateTime.Now - start)); var refList = references.ToList(); Console.WriteLine($"References count: {refList.Count}"); var locations = refList.SelectMany(r => r.Locations).ToList(); Console.WriteLine($"Locations count: {locations.Count}"); } catch (ReflectionTypeLoadException ex) { foreach (var ex2 in ex.LoaderExceptions) Console.WriteLine(ex2); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Storage; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FindReferencesBenchmarks { [Benchmark] public async Task RunFindReferences() { try { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var solutionPath = Path.Combine(roslynRoot, @"C:\github\roslyn\Compilers.sln"); if (!File.Exists(solutionPath)) throw new ArgumentException("Couldn't find Compilers.sln"); Console.Write("Found Compilers.sln: " + Process.GetCurrentProcess().Id); var assemblies = MSBuildMefHostServices.DefaultAssemblies .Add(typeof(AnalyzerRunnerHelper).Assembly) .Add(typeof(FindReferencesBenchmarks).Assembly); var services = MefHostServices.Create(assemblies); var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "9.0" }, }, services); if (workspace == null) throw new ArgumentException("Couldn't create workspace"); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite))); Console.WriteLine("Opening roslyn. Attach to: " + Process.GetCurrentProcess().Id); var start = DateTime.Now; var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result; Console.WriteLine("Finished opening roslyn: " + (DateTime.Now - start)); // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we // perform, including seeing how big the initial string table is. var storageService = workspace.Services.GetService<IPersistentStorageService>(); if (storageService == null) throw new ArgumentException("Couldn't get storage service"); using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None)) { Console.WriteLine(); } // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the // same. var project = solution.Projects.First(p => p.AssemblyName == "Microsoft.CodeAnalysis"); start = DateTime.Now; var compilation = await project.GetCompilationAsync(); Console.WriteLine("Time to get first compilation: " + (DateTime.Now - start)); var type = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.SyntaxToken"); if (type == null) throw new Exception("Couldn't find type"); Console.WriteLine("Starting find-refs"); start = DateTime.Now; var references = await SymbolFinder.FindReferencesAsync(type, solution); Console.WriteLine("Time to find-refs: " + (DateTime.Now - start)); var refList = references.ToList(); Console.WriteLine($"References count: {refList.Count}"); var locations = refList.SelectMany(r => r.Locations).ToList(); Console.WriteLine($"Locations count: {locations.Count}"); } catch (ReflectionTypeLoadException ex) { foreach (var ex2 in ex.LoaderExceptions) Console.WriteLine(ex2); } } } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } var pathToLoad = GetPathToLoad(fullPath); return Assembly.LoadFrom(pathToLoad); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } var pathToLoad = GetPathToLoad(fullPath); return Assembly.LoadFrom(pathToLoad); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #endif
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/VisualStudio/Core/Def/Implementation/CodeModel/ICodeModelInstanceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelInstanceFactory { /// <summary> /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system. /// </summary> /// <remarks> /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another, /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/> /// member should be. The expectation is the implementer of this will do what is necessary and call back into <see cref="IProjectCodeModel.GetOrCreateFileCodeModel(string, object)"/> /// handing it the appropriate parent.</remarks> EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelInstanceFactory { /// <summary> /// Requests the project system to create a <see cref="EnvDTE.FileCodeModel"/> through the project system. /// </summary> /// <remarks> /// This is sometimes necessary because it's possible to go from one <see cref="EnvDTE.FileCodeModel"/> to another, /// but the language service can't create that instance directly, as it doesn't know what the <see cref="EnvDTE.FileCodeModel.Parent"/> /// member should be. The expectation is the implementer of this will do what is necessary and call back into <see cref="IProjectCodeModel.GetOrCreateFileCodeModel(string, object)"/> /// handing it the appropriate parent.</remarks> EnvDTE.FileCodeModel TryCreateFileCodeModelThroughProjectSystem(string filePath); } }
-1
dotnet/roslyn
56,473
Fix MakeLocalFunctionStatic for top-level local function
Fixes https://github.com/dotnet/roslyn/issues/53179
jcouv
"2021-09-17T03:29:26Z"
"2021-09-17T21:32:30Z"
e3756cc7c7229e1509f27ab3de712c59f634c554
a73ef13d7f21ca65c1fc85fa6c6cbde0d075c45d
Fix MakeLocalFunctionStatic for top-level local function. Fixes https://github.com/dotnet/roslyn/issues/53179
./src/Workspaces/Core/Portable/Storage/SQLite/v2/SQLitePersistentStorage.Accessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.SQLite.Interop; using Microsoft.CodeAnalysis.SQLite.v2.Interop; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; #if DEBUG using System.Diagnostics; #endif namespace Microsoft.CodeAnalysis.SQLite.v2 { using static SQLitePersistentStorageConstants; internal partial class SQLitePersistentStorage { /// <summary> /// Abstracts out access to specific tables in the DB. This allows us to share overall /// logic around cancellation/pooling/error-handling/etc, while still hitting different /// db tables. /// </summary> private abstract class Accessor<TKey, TWriteQueueKey, TDatabaseId> { protected readonly SQLitePersistentStorage Storage; // Cache the statement strings we want to execute per accessor. This way we avoid // allocating these strings each time we execute a command. We also cache the prepared // statements (at the connection level) we make for each of these strings. That way we // only incur the parsing cost once. After that, we can use the same prepared statements // and just bind the appropriate values it needs into it. // // values like 0, 1, 2 in the name are the `?`s in the sql string that will need to be // bound to runtime values appropriately when executed. private readonly string _select_rowid_from_main_table_where_0; private readonly string _select_rowid_from_writecache_table_where_0; private readonly string _insert_or_replace_into_writecache_table_values_0_1_2; private readonly string _delete_from_writecache_table; private readonly string _insert_or_replace_into_main_table_select_star_from_writecache_table; public Accessor(SQLitePersistentStorage storage) { var main = Database.Main.GetName(); var writeCache = Database.WriteCache.GetName(); var dataTableName = this.Table switch { Table.Solution => SolutionDataTableName, Table.Project => ProjectDataTableName, Table.Document => DocumentDataTableName, _ => throw ExceptionUtilities.UnexpectedValue(this.Table), }; Storage = storage; _select_rowid_from_main_table_where_0 = $@"select rowid from {main}.{dataTableName} where ""{DataIdColumnName}"" = ?"; _select_rowid_from_writecache_table_where_0 = $@"select rowid from {writeCache}.{dataTableName} where ""{DataIdColumnName}"" = ?"; _insert_or_replace_into_writecache_table_values_0_1_2 = $@"insert or replace into {writeCache}.{dataTableName}(""{DataIdColumnName}"",""{ChecksumColumnName}"",""{DataColumnName}"") values (?,?,?)"; _delete_from_writecache_table = $"delete from {writeCache}.{dataTableName};"; _insert_or_replace_into_main_table_select_star_from_writecache_table = $"insert or replace into {main}.{dataTableName} select * from {writeCache}.{dataTableName};"; } protected abstract Table Table { get; } /// <summary> /// Gets the internal sqlite db-id (effectively the row-id for the doc or proj table, or just the string-id /// for the solution table) for the provided caller key. This db-id will be looked up and returned if a /// mapping already exists for it in the db. Otherwise, a guaranteed unique id will be created for it and /// stored in the db for the future. This allows all associated data to be cheaply associated with the /// simple ID, avoiding lots of db bloat if we used the full <paramref name="key"/> in numerous places. /// </summary> /// <param name="allowWrite">Whether or not the caller owns the write lock and thus is ok with the DB id /// being generated and stored for this component key when it currently does not exist. If <see /// langword="false"/> then failing to find the key will result in <see langword="false"/> being returned. /// </param> protected abstract bool TryGetDatabaseId(SqlConnection connection, TKey key, bool allowWrite, out TDatabaseId dataId); protected abstract void BindFirstParameter(SqlStatement statement, TDatabaseId dataId); protected abstract TWriteQueueKey GetWriteQueueKey(TKey key); protected abstract bool TryGetRowId(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Task<bool> ChecksumMatchesAsync(TKey key, Checksum checksum, CancellationToken cancellationToken) => Storage.PerformReadAsync( static t => t.self.ChecksumMatches(t.key, t.checksum, t.cancellationToken), (self: this, key, checksum, cancellationToken), cancellationToken); private bool ChecksumMatches(TKey key, Checksum checksum, CancellationToken cancellationToken) { var optional = ReadColumn( key, static (self, connection, database, rowId) => self.ReadChecksum(connection, database, rowId), this, cancellationToken); return optional.HasValue && checksum == optional.Value; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Task<Stream?> ReadStreamAsync(TKey key, Checksum? checksum, CancellationToken cancellationToken) => Storage.PerformReadAsync( static t => t.self.ReadStream(t.key, t.checksum, t.cancellationToken), (self: this, key, checksum, cancellationToken), cancellationToken); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] private Stream? ReadStream(TKey key, Checksum? checksum, CancellationToken cancellationToken) { var optional = ReadColumn( key, static (t, connection, database, rowId) => t.self.ReadDataBlob(connection, database, rowId, t.checksum), (self: this, checksum), cancellationToken); Contract.ThrowIfTrue(optional.HasValue && optional.Value == null); return optional.HasValue ? optional.Value : null; } private Optional<T> ReadColumn<T, TData>( TKey key, Func<TData, SqlConnection, Database, long, Optional<T>> readColumn, TData data, CancellationToken cancellationToken) { // We're reading. All current scenarios have this happening under the concurrent/read-only scheduler. // If this assert fires either a bug has been introduced, or there is a valid scenario for a writing // codepath to read a column and this assert should be adjusted. Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ConcurrentScheduler); cancellationToken.ThrowIfCancellationRequested(); if (!Storage._shutdownTokenSource.IsCancellationRequested) { using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection); // We're in the reading-only scheduler path, so we can't allow TryGetDatabaseId to write. Note that // this is ok, and actually provides the semantics we want. Specifically, we can be trying to read // data that either exists in the DB or not. If it doesn't exist in the DB, then it's fine to fail // to map from the key to a DB id (since there's nothing to lookup anyways). And if it does exist // in the db then finding the ID would succeed (without writing) and we could continue. if (TryGetDatabaseId(connection, key, allowWrite: false, out var dataId)) { try { // First, try to see if there was a write to this key in our in-memory db. // If it wasn't in the in-memory write-cache. Check the full on-disk file. var optional = ReadColumnHelper(connection, Database.WriteCache, dataId); if (optional.HasValue) return optional; optional = ReadColumnHelper(connection, Database.Main, dataId); if (optional.HasValue) return optional; } catch (Exception ex) { StorageDatabaseLogger.LogException(ex); } } } return default; Optional<T> ReadColumnHelper(SqlConnection connection, Database database, TDatabaseId dataId) { // Note: it's possible that someone may write to this row between when we get the row ID // above and now. That's fine. We'll just read the new bytes that have been written to // this location. Note that only the data for a row in our system can change, the ID will // always stay the same, and the data will always be valid for our ID. So there is no // safety issue here. return TryGetRowId(connection, database, dataId, out var writeCacheRowId) ? readColumn(data, connection, database, writeCacheRowId) : default; } } public Task<bool> WriteStreamAsync(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken) => Storage.PerformWriteAsync( static t => t.self.WriteStream(t.key, t.stream, t.checksum, t.cancellationToken), (self: this, key, stream, checksum, cancellationToken), cancellationToken); private bool WriteStream(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken) { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler); cancellationToken.ThrowIfCancellationRequested(); if (!Storage._shutdownTokenSource.IsCancellationRequested) { using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection); // Determine the appropriate data-id to store this stream at. We already are running // with an exclusive write lock on the DB, so it's safe for us to write the data id to // the db on this connection if we need to. if (TryGetDatabaseId(connection, key, allowWrite: true, out var dataId)) { checksum ??= Checksum.Null; Span<byte> checksumBytes = stackalloc byte[Checksum.HashSize]; checksum.WriteTo(checksumBytes); var (dataBytes, dataLength, dataPooled) = GetBytes(stream); // Write the information into the in-memory write-cache. Later on a background task // will move it from the in-memory cache to the on-disk db in a bulk transaction. InsertOrReplaceBlobIntoWriteCache( connection, dataId, checksumBytes, new ReadOnlySpan<byte>(dataBytes, 0, dataLength)); if (dataPooled) ReturnPooledBytes(dataBytes); return true; } } return false; } private Optional<Stream> ReadDataBlob( SqlConnection connection, Database database, long rowId, Checksum? checksum) { // Have to run the blob reading in a transaction. This is necessary // for two reasons. First, blob reading outside a transaction is not // safe to do with the sqlite API. It may produce corrupt bits if // another thread is writing to the blob. Second, if a checksum was // passed in, we need to validate that the checksums match. This is // only safe if we are in a transaction and no-one else can race with // us. return connection.RunInTransaction( static t => { // If we were passed a checksum, make sure it matches what we have // stored in the table already. If they don't match, don't read // out the data value at all. if (t.checksum != null && !t.self.ChecksumsMatch_MustRunInTransaction(t.connection, t.database, t.rowId, t.checksum)) { return default; } return t.connection.ReadDataBlob_MustRunInTransaction(t.database, t.self.Table, t.rowId); }, (self: this, connection, database, checksum, rowId)); } private Optional<Checksum.HashData> ReadChecksum( SqlConnection connection, Database database, long rowId) { // Have to run the checksum reading in a transaction. This is necessary as blob reading outside a // transaction is not safe to do with the sqlite API. It may produce corrupt bits if another thread is // writing to the blob. return connection.RunInTransaction( static t => t.connection.ReadChecksum_MustRunInTransaction(t.database, t.self.Table, t.rowId), (self: this, connection, database, rowId)); } private bool ChecksumsMatch_MustRunInTransaction(SqlConnection connection, Database database, long rowId, Checksum checksum) { var storedChecksum = connection.ReadChecksum_MustRunInTransaction(database, Table, rowId); return storedChecksum.HasValue && checksum == storedChecksum.Value; } #pragma warning disable CA1822 // Mark members as static - instance members used in Debug protected bool GetAndVerifyRowId(SqlConnection connection, Database database, long dataId, out long rowId) #pragma warning restore CA1822 // Mark members as static { // For the Document and Project tables, our dataId is our rowId: // // https://sqlite.org/lang_createtable.html // if a rowid table has a primary key that consists of a single column and the // declared type of that column is "INTEGER" in any mixture of upper and lower // case, then the column becomes an alias for the rowid. Such a column is usually // referred to as an "integer primary key". A PRIMARY KEY column only becomes an // integer primary key if the declared type name is exactly "INTEGER" #if DEBUG // make sure that if we actually request the rowId from the database that it // is equal to our data id. Only do this in debug as this can be expensive // and we definitely do not want to do this in release. if (GetActualRowIdFromDatabase(connection, database, (TDatabaseId)(object)dataId, out rowId)) { Debug.Assert(dataId == rowId); } #endif // Can just return out dataId as the rowId without actually having to hit the // database at all. rowId = dataId; return true; } protected bool GetActualRowIdFromDatabase(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId) { // See https://sqlite.org/autoinc.html // > In SQLite, table rows normally have a 64-bit signed integer ROWID which is // unique among all rows in the same table. (WITHOUT ROWID tables are the exception.) // // You can access the ROWID of an SQLite table using one of the special column names // ROWID, _ROWID_, or OID. Except if you declare an ordinary table column to use one // of those special names, then the use of that name will refer to the declared column // not to the internal ROWID. using var resettableStatement = connection.GetResettableStatement(database == Database.WriteCache ? _select_rowid_from_writecache_table_where_0 : _select_rowid_from_main_table_where_0); var statement = resettableStatement.Statement; BindFirstParameter(statement, dataId); var stepResult = statement.Step(); if (stepResult == Result.ROW) { rowId = statement.GetInt64At(columnIndex: 0); return true; } rowId = -1; return false; } private void InsertOrReplaceBlobIntoWriteCache( SqlConnection connection, TDatabaseId dataId, ReadOnlySpan<byte> checksumBytes, ReadOnlySpan<byte> dataBytes) { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler); using (var resettableStatement = connection.GetResettableStatement(_insert_or_replace_into_writecache_table_values_0_1_2)) { var statement = resettableStatement.Statement; // Binding indices are 1 based. BindFirstParameter(statement, dataId); statement.BindBlobParameter(parameterIndex: 2, checksumBytes); statement.BindBlobParameter(parameterIndex: 3, dataBytes); statement.Step(); } // Let the storage system know it should flush this information // to disk in the future. Storage.EnqueueFlushTask(); } public void FlushInMemoryDataToDisk_MustRunInTransaction(SqlConnection connection) { if (!connection.IsInTransaction) { throw new InvalidOperationException("Must flush tables within a transaction to ensure consistency"); } // Efficient call to sqlite to just fully copy all data from one table to the // other. No need to actually do any reading/writing of the data ourselves. using (var statement = connection.GetResettableStatement(_insert_or_replace_into_main_table_select_star_from_writecache_table)) { statement.Statement.Step(); } // Now, just delete all the data from the write cache. using (var statement = connection.GetResettableStatement(_delete_from_writecache_table)) { statement.Statement.Step(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.SQLite.Interop; using Microsoft.CodeAnalysis.SQLite.v2.Interop; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; #if DEBUG using System.Diagnostics; #endif namespace Microsoft.CodeAnalysis.SQLite.v2 { using static SQLitePersistentStorageConstants; internal partial class SQLitePersistentStorage { /// <summary> /// Abstracts out access to specific tables in the DB. This allows us to share overall /// logic around cancellation/pooling/error-handling/etc, while still hitting different /// db tables. /// </summary> private abstract class Accessor<TKey, TWriteQueueKey, TDatabaseId> { protected readonly SQLitePersistentStorage Storage; // Cache the statement strings we want to execute per accessor. This way we avoid // allocating these strings each time we execute a command. We also cache the prepared // statements (at the connection level) we make for each of these strings. That way we // only incur the parsing cost once. After that, we can use the same prepared statements // and just bind the appropriate values it needs into it. // // values like 0, 1, 2 in the name are the `?`s in the sql string that will need to be // bound to runtime values appropriately when executed. private readonly string _select_rowid_from_main_table_where_0; private readonly string _select_rowid_from_writecache_table_where_0; private readonly string _insert_or_replace_into_writecache_table_values_0_1_2; private readonly string _delete_from_writecache_table; private readonly string _insert_or_replace_into_main_table_select_star_from_writecache_table; public Accessor(SQLitePersistentStorage storage) { var main = Database.Main.GetName(); var writeCache = Database.WriteCache.GetName(); var dataTableName = this.Table switch { Table.Solution => SolutionDataTableName, Table.Project => ProjectDataTableName, Table.Document => DocumentDataTableName, _ => throw ExceptionUtilities.UnexpectedValue(this.Table), }; Storage = storage; _select_rowid_from_main_table_where_0 = $@"select rowid from {main}.{dataTableName} where ""{DataIdColumnName}"" = ?"; _select_rowid_from_writecache_table_where_0 = $@"select rowid from {writeCache}.{dataTableName} where ""{DataIdColumnName}"" = ?"; _insert_or_replace_into_writecache_table_values_0_1_2 = $@"insert or replace into {writeCache}.{dataTableName}(""{DataIdColumnName}"",""{ChecksumColumnName}"",""{DataColumnName}"") values (?,?,?)"; _delete_from_writecache_table = $"delete from {writeCache}.{dataTableName};"; _insert_or_replace_into_main_table_select_star_from_writecache_table = $"insert or replace into {main}.{dataTableName} select * from {writeCache}.{dataTableName};"; } protected abstract Table Table { get; } /// <summary> /// Gets the internal sqlite db-id (effectively the row-id for the doc or proj table, or just the string-id /// for the solution table) for the provided caller key. This db-id will be looked up and returned if a /// mapping already exists for it in the db. Otherwise, a guaranteed unique id will be created for it and /// stored in the db for the future. This allows all associated data to be cheaply associated with the /// simple ID, avoiding lots of db bloat if we used the full <paramref name="key"/> in numerous places. /// </summary> /// <param name="allowWrite">Whether or not the caller owns the write lock and thus is ok with the DB id /// being generated and stored for this component key when it currently does not exist. If <see /// langword="false"/> then failing to find the key will result in <see langword="false"/> being returned. /// </param> protected abstract bool TryGetDatabaseId(SqlConnection connection, TKey key, bool allowWrite, out TDatabaseId dataId); protected abstract void BindFirstParameter(SqlStatement statement, TDatabaseId dataId); protected abstract TWriteQueueKey GetWriteQueueKey(TKey key); protected abstract bool TryGetRowId(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Task<bool> ChecksumMatchesAsync(TKey key, Checksum checksum, CancellationToken cancellationToken) => Storage.PerformReadAsync( static t => t.self.ChecksumMatches(t.key, t.checksum, t.cancellationToken), (self: this, key, checksum, cancellationToken), cancellationToken); private bool ChecksumMatches(TKey key, Checksum checksum, CancellationToken cancellationToken) { var optional = ReadColumn( key, static (self, connection, database, rowId) => self.ReadChecksum(connection, database, rowId), this, cancellationToken); return optional.HasValue && checksum == optional.Value; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] public Task<Stream?> ReadStreamAsync(TKey key, Checksum? checksum, CancellationToken cancellationToken) => Storage.PerformReadAsync( static t => t.self.ReadStream(t.key, t.checksum, t.cancellationToken), (self: this, key, checksum, cancellationToken), cancellationToken); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", AllowCaptures = false)] private Stream? ReadStream(TKey key, Checksum? checksum, CancellationToken cancellationToken) { var optional = ReadColumn( key, static (t, connection, database, rowId) => t.self.ReadDataBlob(connection, database, rowId, t.checksum), (self: this, checksum), cancellationToken); Contract.ThrowIfTrue(optional.HasValue && optional.Value == null); return optional.HasValue ? optional.Value : null; } private Optional<T> ReadColumn<T, TData>( TKey key, Func<TData, SqlConnection, Database, long, Optional<T>> readColumn, TData data, CancellationToken cancellationToken) { // We're reading. All current scenarios have this happening under the concurrent/read-only scheduler. // If this assert fires either a bug has been introduced, or there is a valid scenario for a writing // codepath to read a column and this assert should be adjusted. Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ConcurrentScheduler); cancellationToken.ThrowIfCancellationRequested(); if (!Storage._shutdownTokenSource.IsCancellationRequested) { using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection); // We're in the reading-only scheduler path, so we can't allow TryGetDatabaseId to write. Note that // this is ok, and actually provides the semantics we want. Specifically, we can be trying to read // data that either exists in the DB or not. If it doesn't exist in the DB, then it's fine to fail // to map from the key to a DB id (since there's nothing to lookup anyways). And if it does exist // in the db then finding the ID would succeed (without writing) and we could continue. if (TryGetDatabaseId(connection, key, allowWrite: false, out var dataId)) { try { // First, try to see if there was a write to this key in our in-memory db. // If it wasn't in the in-memory write-cache. Check the full on-disk file. var optional = ReadColumnHelper(connection, Database.WriteCache, dataId); if (optional.HasValue) return optional; optional = ReadColumnHelper(connection, Database.Main, dataId); if (optional.HasValue) return optional; } catch (Exception ex) { StorageDatabaseLogger.LogException(ex); } } } return default; Optional<T> ReadColumnHelper(SqlConnection connection, Database database, TDatabaseId dataId) { // Note: it's possible that someone may write to this row between when we get the row ID // above and now. That's fine. We'll just read the new bytes that have been written to // this location. Note that only the data for a row in our system can change, the ID will // always stay the same, and the data will always be valid for our ID. So there is no // safety issue here. return TryGetRowId(connection, database, dataId, out var writeCacheRowId) ? readColumn(data, connection, database, writeCacheRowId) : default; } } public Task<bool> WriteStreamAsync(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken) => Storage.PerformWriteAsync( static t => t.self.WriteStream(t.key, t.stream, t.checksum, t.cancellationToken), (self: this, key, stream, checksum, cancellationToken), cancellationToken); private bool WriteStream(TKey key, Stream stream, Checksum? checksum, CancellationToken cancellationToken) { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler); cancellationToken.ThrowIfCancellationRequested(); if (!Storage._shutdownTokenSource.IsCancellationRequested) { using var _ = Storage._connectionPool.Target.GetPooledConnection(out var connection); // Determine the appropriate data-id to store this stream at. We already are running // with an exclusive write lock on the DB, so it's safe for us to write the data id to // the db on this connection if we need to. if (TryGetDatabaseId(connection, key, allowWrite: true, out var dataId)) { checksum ??= Checksum.Null; Span<byte> checksumBytes = stackalloc byte[Checksum.HashSize]; checksum.WriteTo(checksumBytes); var (dataBytes, dataLength, dataPooled) = GetBytes(stream); // Write the information into the in-memory write-cache. Later on a background task // will move it from the in-memory cache to the on-disk db in a bulk transaction. InsertOrReplaceBlobIntoWriteCache( connection, dataId, checksumBytes, new ReadOnlySpan<byte>(dataBytes, 0, dataLength)); if (dataPooled) ReturnPooledBytes(dataBytes); return true; } } return false; } private Optional<Stream> ReadDataBlob( SqlConnection connection, Database database, long rowId, Checksum? checksum) { // Have to run the blob reading in a transaction. This is necessary // for two reasons. First, blob reading outside a transaction is not // safe to do with the sqlite API. It may produce corrupt bits if // another thread is writing to the blob. Second, if a checksum was // passed in, we need to validate that the checksums match. This is // only safe if we are in a transaction and no-one else can race with // us. return connection.RunInTransaction( static t => { // If we were passed a checksum, make sure it matches what we have // stored in the table already. If they don't match, don't read // out the data value at all. if (t.checksum != null && !t.self.ChecksumsMatch_MustRunInTransaction(t.connection, t.database, t.rowId, t.checksum)) { return default; } return t.connection.ReadDataBlob_MustRunInTransaction(t.database, t.self.Table, t.rowId); }, (self: this, connection, database, checksum, rowId)); } private Optional<Checksum.HashData> ReadChecksum( SqlConnection connection, Database database, long rowId) { // Have to run the checksum reading in a transaction. This is necessary as blob reading outside a // transaction is not safe to do with the sqlite API. It may produce corrupt bits if another thread is // writing to the blob. return connection.RunInTransaction( static t => t.connection.ReadChecksum_MustRunInTransaction(t.database, t.self.Table, t.rowId), (self: this, connection, database, rowId)); } private bool ChecksumsMatch_MustRunInTransaction(SqlConnection connection, Database database, long rowId, Checksum checksum) { var storedChecksum = connection.ReadChecksum_MustRunInTransaction(database, Table, rowId); return storedChecksum.HasValue && checksum == storedChecksum.Value; } #pragma warning disable CA1822 // Mark members as static - instance members used in Debug protected bool GetAndVerifyRowId(SqlConnection connection, Database database, long dataId, out long rowId) #pragma warning restore CA1822 // Mark members as static { // For the Document and Project tables, our dataId is our rowId: // // https://sqlite.org/lang_createtable.html // if a rowid table has a primary key that consists of a single column and the // declared type of that column is "INTEGER" in any mixture of upper and lower // case, then the column becomes an alias for the rowid. Such a column is usually // referred to as an "integer primary key". A PRIMARY KEY column only becomes an // integer primary key if the declared type name is exactly "INTEGER" #if DEBUG // make sure that if we actually request the rowId from the database that it // is equal to our data id. Only do this in debug as this can be expensive // and we definitely do not want to do this in release. if (GetActualRowIdFromDatabase(connection, database, (TDatabaseId)(object)dataId, out rowId)) { Debug.Assert(dataId == rowId); } #endif // Can just return out dataId as the rowId without actually having to hit the // database at all. rowId = dataId; return true; } protected bool GetActualRowIdFromDatabase(SqlConnection connection, Database database, TDatabaseId dataId, out long rowId) { // See https://sqlite.org/autoinc.html // > In SQLite, table rows normally have a 64-bit signed integer ROWID which is // unique among all rows in the same table. (WITHOUT ROWID tables are the exception.) // // You can access the ROWID of an SQLite table using one of the special column names // ROWID, _ROWID_, or OID. Except if you declare an ordinary table column to use one // of those special names, then the use of that name will refer to the declared column // not to the internal ROWID. using var resettableStatement = connection.GetResettableStatement(database == Database.WriteCache ? _select_rowid_from_writecache_table_where_0 : _select_rowid_from_main_table_where_0); var statement = resettableStatement.Statement; BindFirstParameter(statement, dataId); var stepResult = statement.Step(); if (stepResult == Result.ROW) { rowId = statement.GetInt64At(columnIndex: 0); return true; } rowId = -1; return false; } private void InsertOrReplaceBlobIntoWriteCache( SqlConnection connection, TDatabaseId dataId, ReadOnlySpan<byte> checksumBytes, ReadOnlySpan<byte> dataBytes) { // We're writing. This better always be under the exclusive scheduler. Contract.ThrowIfFalse(TaskScheduler.Current == Storage._connectionPoolService.Scheduler.ExclusiveScheduler); using (var resettableStatement = connection.GetResettableStatement(_insert_or_replace_into_writecache_table_values_0_1_2)) { var statement = resettableStatement.Statement; // Binding indices are 1 based. BindFirstParameter(statement, dataId); statement.BindBlobParameter(parameterIndex: 2, checksumBytes); statement.BindBlobParameter(parameterIndex: 3, dataBytes); statement.Step(); } // Let the storage system know it should flush this information // to disk in the future. Storage.EnqueueFlushTask(); } public void FlushInMemoryDataToDisk_MustRunInTransaction(SqlConnection connection) { if (!connection.IsInTransaction) { throw new InvalidOperationException("Must flush tables within a transaction to ensure consistency"); } // Efficient call to sqlite to just fully copy all data from one table to the // other. No need to actually do any reading/writing of the data ourselves. using (var statement = connection.GetResettableStatement(_insert_or_replace_into_main_table_select_star_from_writecache_table)) { statement.Statement.Step(); } // Now, just delete all the data from the write cache. using (var statement = connection.GetResettableStatement(_delete_from_writecache_table)) { statement.Statement.Step(); } } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginGlyph.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal partial class InheritanceMarginGlyph { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; private readonly IAsynchronousOperationListener _listener; public InheritanceMarginGlyph( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag, IWpfTextView textView, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; _textView = textView; _listener = listener; InitializeComponent(); var viewModel = InheritanceMarginGlyphViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel); DataContext = viewModel; ContextMenu.DataContext = viewModel; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource("ToolTipStyle") }; } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { if (this.ContextMenu != null) { this.ContextMenu.IsOpen = true; e.Handled = true; } } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); var token = _listener.BeginAsyncOperation(nameof(TargetMenuItem_OnClick)); TargetMenuItem_OnClickAsync(viewModel).CompletesAsyncOperation(token); } } private async Task TargetMenuItem_OnClickAsync(TargetMenuItemViewModel viewModel) { using var context = _operationExecutor.BeginExecute( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false); var cancellationToken = context.UserCancellationToken; var rehydrated = await viewModel.DefinitionItem.TryRehydrateAsync(cancellationToken).ConfigureAwait(false); if (rehydrated == null) return; await _streamingFindUsagesPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, _workspace, string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent), ImmutableArray.Create<DefinitionItem>(rehydrated), cancellationToken).ConfigureAwait(false); } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { // If mouse is still hovering. Don't reset the color. The context menu might be closed because user clicks within the margin if (!IsMouseOver) { ResetBorderToInitialColor(); } // Move the focus back to textView when the context menu is closed. // It ensures the focus won't be left at the margin ResetFocus(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginGlyphViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Header // Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Header // -> Target1 // -> Target2 // -> method Foo -> Header // -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } private void ResetFocus() { if (!_textView.HasAggregateFocus) { var visualElement = _textView.VisualElement; if (visualElement.Focusable) { Keyboard.Focus(visualElement); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginGlyph : Button { private const string ToolTipStyleKey = "ToolTipStyle"; private static readonly object s_toolTipPlaceholder = new(); private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; private readonly IAsynchronousOperationListener _listener; public InheritanceMarginGlyph( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag, IWpfTextView textView, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; _textView = textView; _listener = listener; Background = Brushes.Transparent; BorderBrush = Brushes.Transparent; Click += InheritanceMargin_OnClick; MouseEnter += InheritanceMargin_OnMouseEnter; MouseLeave += InheritanceMargin_OnMouseLeave; Resources.Add(ToolTipStyleKey, new Style(typeof(ToolTip)) { Setters = { new Setter(BackgroundProperty, new DynamicResourceExtension(EnvironmentColors.ToolTipBrushKey)), new Setter(BorderBrushProperty, new DynamicResourceExtension(EnvironmentColors.ToolTipBorderBrushKey)), new Setter(ForegroundProperty, new DynamicResourceExtension(EnvironmentColors.ToolTipTextBrushKey)), }, }); var viewModel = InheritanceMarginGlyphViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel); SetValue(AutomationProperties.NameProperty, viewModel.AutomationName); // Control template only shows the image var templateBorder = new FrameworkElementFactory(typeof(Border), "Border"); templateBorder.SetValue(Border.BorderThicknessProperty, new Thickness(1)); templateBorder.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(BackgroundProperty)); templateBorder.SetValue(Border.BorderBrushProperty, new TemplateBindingExtension(BorderBrushProperty)); var templateImage = new FrameworkElementFactory(typeof(CrispImage)); templateImage.SetValue(CrispImage.MonikerProperty, viewModel.ImageMoniker); templateImage.SetValue(CrispImage.ScaleFactorProperty, viewModel.ScaleFactor); templateBorder.AppendChild(templateImage); Template = new ControlTemplate { VisualTree = templateBorder }; DataContext = viewModel; // Add the context menu and tool tip as placeholders ContextMenu = new ContextMenu(); ToolTip = s_toolTipPlaceholder; } protected override void OnToolTipOpening(ToolTipEventArgs e) { if (ToolTip == s_toolTipPlaceholder) { var viewModel = (InheritanceMarginGlyphViewModel)DataContext; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource(ToolTipStyleKey) }; } base.OnToolTipOpening(e); } protected override void OnContextMenuOpening(ContextMenuEventArgs e) { LazyInitializeContextMenu(); base.OnContextMenuOpening(e); } private void LazyInitializeContextMenu() { if (ContextMenu is not InheritanceMarginContextMenu) { var viewModel = (InheritanceMarginGlyphViewModel)DataContext; ContextMenu = new InheritanceMarginContextMenu(_threadingContext, _streamingFindUsagesPresenter, _operationExecutor, _workspace, _textView, _listener); ContextMenu.DataContext = viewModel; ContextMenu.ItemsSource = viewModel.MenuItemViewModels; ContextMenu.Opened += ContextMenu_OnOpen; ContextMenu.Closed += ContextMenu_OnClose; } } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { LazyInitializeContextMenu(); ContextMenu.IsOpen = true; e.Handled = true; } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { // If mouse is still hovering. Don't reset the color. The context menu might be closed because user clicks within the margin if (!IsMouseOver) { ResetBorderToInitialColor(); } // Move the focus back to textView when the context menu is closed. // It ensures the focus won't be left at the margin ResetFocus(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginGlyphViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Header // Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Header // -> Target1 // -> Target2 // -> method Foo -> Header // -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } private void ResetFocus() { if (!_textView.HasAggregateFocus) { var visualElement = _textView.VisualElement; if (visualElement.Focusable) { Keyboard.Focus(visualElement); } } } } }
1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMarginGlyphViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginGlyphViewModel { /// <summary> /// ImageMoniker used for the margin. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// Tooltip for the margin. /// </summary> public TextBlock ToolTipTextBlock { get; } /// <summary> /// Text used for automation. /// </summary> public string AutomationName { get; } /// <summary> /// ViewModels for the context menu items. /// </summary> public ImmutableArray<MenuItemViewModel> MenuItemViewModels { get; } /// <summary> /// Scale factor for the margin. /// </summary> public double ScaleFactor { get; } // Internal for testing purpose internal InheritanceMarginGlyphViewModel( ImageMoniker imageMoniker, TextBlock toolTipTextBlock, string automationName, double scaleFactor, ImmutableArray<MenuItemViewModel> menuItemViewModels) { ImageMoniker = imageMoniker; ToolTipTextBlock = toolTipTextBlock; AutomationName = automationName; MenuItemViewModels = menuItemViewModels; ScaleFactor = scaleFactor; } public static InheritanceMarginGlyphViewModel Create( ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, InheritanceMarginTag tag, double zoomLevel) { var members = tag.MembersOnLine; // ZoomLevel is 100 based. (e.g. 150%, 100%) // ScaleFactor is 1 based. (e.g. 1.5, 1) var scaleFactor = zoomLevel / 100; if (members.Length == 1) { var member = tag.MembersOnLine[0]; // Here we want to show a classified text with loc text, // e.g. 'Bar' is inherited. // But the classified text are inlines, so can't directly use string.format to generate the string var inlines = member.DisplayTexts.ToInlines(classificationFormatMap, classificationTypeMap); var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal); var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder]; var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..]; inlines.Insert(0, new Run(prefixString)); inlines.Add(new Run(suffixString)); var toolTipTextBlock = inlines.ToTextBlock(classificationFormatMap); toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight; var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText()); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems); return new InheritanceMarginGlyphViewModel(tag.Moniker, toolTipTextBlock, automationName, scaleFactor, menuItemViewModels); } else { var textBlock = new TextBlock { Text = ServicesVSResources.Multiple_members_are_inherited }; // Same automation name can't be set for control for accessibility purpose. So add the line number info. var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine); return new InheritanceMarginGlyphViewModel(tag.Moniker, textBlock, automationName, scaleFactor, menuItemViewModels); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal class InheritanceMarginGlyphViewModel { private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMap _classificationFormatMap; private readonly InheritanceMarginTag _tag; private TextBlock? _lazyToolTipTextBlock; /// <summary> /// ImageMoniker used for the margin. /// </summary> public ImageMoniker ImageMoniker => _tag.Moniker; /// <summary> /// Tooltip for the margin. /// </summary> public TextBlock ToolTipTextBlock { get { if (_lazyToolTipTextBlock is null) { var members = _tag.MembersOnLine; if (members.Length == 1) { var member = _tag.MembersOnLine[0]; // Here we want to show a classified text with loc text, // e.g. 'Bar' is inherited. // But the classified text are inlines, so can't directly use string.format to generate the string var inlines = member.DisplayTexts.ToInlines(_classificationFormatMap, _classificationTypeMap); var startOfThePlaceholder = ServicesVSResources._0_is_inherited.IndexOf("{0}", StringComparison.Ordinal); var prefixString = ServicesVSResources._0_is_inherited[..startOfThePlaceholder]; var suffixString = ServicesVSResources._0_is_inherited[(startOfThePlaceholder + "{0}".Length)..]; inlines.Insert(0, new Run(prefixString)); inlines.Add(new Run(suffixString)); var toolTipTextBlock = inlines.ToTextBlock(_classificationFormatMap); toolTipTextBlock.FlowDirection = FlowDirection.LeftToRight; _lazyToolTipTextBlock = toolTipTextBlock; } else { _lazyToolTipTextBlock = new TextBlock { Text = ServicesVSResources.Multiple_members_are_inherited }; } } return _lazyToolTipTextBlock; } } /// <summary> /// Text used for automation. /// </summary> public string AutomationName { get; } /// <summary> /// ViewModels for the context menu items. /// </summary> public ImmutableArray<MenuItemViewModel> MenuItemViewModels { get; } /// <summary> /// Scale factor for the margin. /// </summary> public double ScaleFactor { get; } private InheritanceMarginGlyphViewModel( InheritanceMarginTag tag, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, string automationName, double scaleFactor, ImmutableArray<MenuItemViewModel> menuItemViewModels) { _classificationTypeMap = classificationTypeMap; _classificationFormatMap = classificationFormatMap; _tag = tag; AutomationName = automationName; MenuItemViewModels = menuItemViewModels; ScaleFactor = scaleFactor; } public static InheritanceMarginGlyphViewModel Create( ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, InheritanceMarginTag tag, double zoomLevel) { var members = tag.MembersOnLine; // ZoomLevel is 100 based. (e.g. 150%, 100%) // ScaleFactor is 1 based. (e.g. 1.5, 1) var scaleFactor = zoomLevel / 100; if (members.Length == 1) { var member = tag.MembersOnLine[0]; var automationName = string.Format(ServicesVSResources._0_is_inherited, member.DisplayTexts.JoinText()); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForSingleMember(member.TargetItems); return new InheritanceMarginGlyphViewModel(tag, classificationTypeMap, classificationFormatMap, automationName, scaleFactor, menuItemViewModels); } else { // Same automation name can't be set for control for accessibility purpose. So add the line number info. var automationName = string.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, tag.LineNumber); var menuItemViewModels = InheritanceMarginHelpers.CreateMenuItemViewModelsForMultipleMembers(tag.MembersOnLine); return new InheritanceMarginGlyphViewModel(tag, classificationTypeMap, classificationFormatMap, automationName, scaleFactor, menuItemViewModels); } } } }
1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/VisualStudio/Core/Test/InheritanceMargin/InheritanceMarginViewModelTests.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.Text Imports System.Threading Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Documents Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InheritanceMargin Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph Imports Microsoft.VisualStudio.Text.Classification Imports Microsoft.VisualStudio.Threading Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.InheritanceMargin <Trait(Traits.Feature, Traits.Features.InheritanceMargin)> <UseExportProvider> Public Class InheritanceMarginViewModelTests Private Shared s_defaultMargin As Thickness = New Thickness(4, 1, 4, 1) Private Shared s_indentMargin As Thickness = New Thickness(22, 1, 4, 1) Private Shared Async Function VerifyAsync(markup As String, languageName As String, expectedViewModels As Dictionary(Of Integer, InheritanceMarginGlyphViewModel)) As Task ' Add an lf before the document so that the line number starts ' with 1, which meets the line number in the editor (but in fact all things start from 0) Dim workspaceFile = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= vbLf %> <%= markup.Replace(vbCrLf, vbLf) %> </Document> </Project> </Workspace> Dim cancellationToken As CancellationToken = CancellationToken.None Using workspace = TestWorkspace.Create(workspaceFile) Dim testDocument = workspace.Documents.Single() Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim service = document.GetRequiredLanguageService(Of IInheritanceMarginService) Dim classificationTypeMap = workspace.ExportProvider.GetExportedValue(Of ClassificationTypeMap) Dim classificationFormatMap = workspace.ExportProvider.GetExportedValue(Of IClassificationFormatMapService) ' For these tests, we need to be on UI thread, so don't call ConfigureAwait(False) Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(True) Dim inheritanceItems = Await service.GetInheritanceMemberItemsAsync(document, root.FullSpan, cancellationToken).ConfigureAwait(True) Dim acutalLineToTagDictionary = inheritanceItems.GroupBy(Function(item) item.LineNumber) _ .ToDictionary(Function(grouping) grouping.Key, Function(grouping) Dim lineNumber = grouping.Key Dim items = grouping.Select(Function(g) g).ToImmutableArray() Return New InheritanceMarginTag(workspace, lineNumber, items) End Function) Assert.Equal(expectedViewModels.Count, acutalLineToTagDictionary.Count) For Each kvp In expectedViewModels Dim lineNumber = kvp.Key Dim expectedViewModel = kvp.Value Assert.True(acutalLineToTagDictionary.ContainsKey(lineNumber)) Dim acutalTag = acutalLineToTagDictionary(lineNumber) ' Editor TestView zoom level is 100 based. Dim actualViewModel = InheritanceMarginGlyphViewModel.Create( classificationTypeMap, classificationFormatMap.GetClassificationFormatMap("tooltip"), acutalTag, 100) VerifyTwoViewModelAreSame(expectedViewModel, actualViewModel) Next End Using End Function Private Shared Sub VerifyTwoViewModelAreSame(expected As InheritanceMarginGlyphViewModel, actual As InheritanceMarginGlyphViewModel) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Dim actualTextGetFromTextBlock = actual.ToolTipTextBlock.Inlines _ .OfType(Of Run).Select(Function(run) run.Text) _ .Aggregate(Function(text1, text2) text1 + text2) ' When the text block is created, a unicode 'left to right' would be inserted between the space. ' Make sure it is removed. Dim leftToRightMarker = Char.ConvertFromUtf32(&H200E) Dim actualText = actualTextGetFromTextBlock.Replace(leftToRightMarker, String.Empty) Assert.Equal(expected.ToolTipTextBlock.Text, actualText) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.MenuItemViewModels.Length, actual.MenuItemViewModels.Length) Assert.Equal(expected.ScaleFactor, actual.ScaleFactor) For i = 0 To expected.MenuItemViewModels.Length - 1 Dim expectedMenuItem = expected.MenuItemViewModels(i) Dim actualMenuItem = actual.MenuItemViewModels(i) VerifyMenuItem(expectedMenuItem, actualMenuItem) Next End Sub Private Shared Sub VerifyMenuItem(expected As MenuItemViewModel, actual As MenuItemViewModel) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.DisplayContent, actual.DisplayContent) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Dim expectedTargetMenuItem = TryCast(expected, TargetMenuItemViewModel) Dim acutalTargetMenuItem = TryCast(actual, TargetMenuItemViewModel) If expectedTargetMenuItem IsNot Nothing AndAlso acutalTargetMenuItem IsNot Nothing Then Return End If Dim expectedMemberMenuItem = TryCast(expected, MemberMenuItemViewModel) Dim acutalMemberMenuItem = TryCast(actual, MemberMenuItemViewModel) If expectedMemberMenuItem IsNot Nothing AndAlso acutalMemberMenuItem IsNot Nothing Then Assert.Equal(expectedMemberMenuItem.Targets.Length, acutalMemberMenuItem.Targets.Length) For i = 0 To expectedMemberMenuItem.Targets.Length - 1 VerifyMenuItem(expectedMemberMenuItem.Targets(i), acutalMemberMenuItem.Targets(i)) Next Return End If ' At this stage, both of the items should be header Assert.True(TypeOf expected Is HeaderMenuItemViewModel) Assert.True(TypeOf actual Is HeaderMenuItemViewModel) End Sub Private Shared Function CreateTextBlock(text As String) As TextBlock Return New TextBlock With { .Text = text } End Function <WpfFact> Public Function TestClassImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar { } public class Bar : IBar { }" Dim tooltipTextForIBar = String.Format(ServicesVSResources._0_is_inherited, "interface IBar") Dim targetForIBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types)). Add(New TargetMenuItemViewModel("Bar", KnownMonikers.ClassPublic, "Bar", Nothing)) Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim targetForBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces)). Add(New TargetMenuItemViewModel("IBar", KnownMonikers.InterfacePublic, "IBar", Nothing)) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From { {2, New InheritanceMarginGlyphViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar), tooltipTextForIBar, 1, targetForIBar)}, {5, New InheritanceMarginGlyphViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForBar), tooltipTextForBar, 1, targetForBar)}}) End Function <WpfFact> Public Function TestClassOverridesAbstractClassRelationship() As Task Dim markup = " public abstract class AbsBar { public abstract void Foo(); } public class Bar : AbsBar { public override void Foo(); }" Dim tooltipTextForAbsBar = String.Format(ServicesVSResources._0_is_inherited, "class AbsBar") Dim targetForAbsBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Derived_types, KnownMonikers.Overridden, ServicesVSResources.Derived_types)). Add(New TargetMenuItemViewModel("Bar", KnownMonikers.ClassPublic, "Bar", Nothing)) Dim tooltipTextForAbstractFoo = String.Format(ServicesVSResources._0_is_inherited, "abstract void AbsBar.Foo()") Dim targetForAbsFoo = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overriding_members, KnownMonikers.Overridden, ServicesVSResources.Overriding_members)). Add(New TargetMenuItemViewModel("Bar.Foo", KnownMonikers.MethodPublic, "Bar.Foo", Nothing)) Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim targetForBar = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Base_Types, KnownMonikers.Overriding, ServicesVSResources.Base_Types)). Add(New TargetMenuItemViewModel("AbsBar", KnownMonikers.ClassPublic, "AbsBar", Nothing)) Dim tooltipTextForOverrideFoo = String.Format(ServicesVSResources._0_is_inherited, "override void Bar.Foo()") Dim targetForOverrideFoo = ImmutableArray.Create(Of MenuItemViewModel)(New HeaderMenuItemViewModel(ServicesVSResources.Overridden_members, KnownMonikers.Overriding, ServicesVSResources.Overridden_members)). Add(New TargetMenuItemViewModel("AbsBar.Foo", KnownMonikers.MethodPublic, "AbsBar.Foo", Nothing)) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From { {2, New InheritanceMarginGlyphViewModel( KnownMonikers.Overridden, CreateTextBlock(tooltipTextForAbsBar), tooltipTextForAbsBar, 1, targetForAbsBar)}, {4, New InheritanceMarginGlyphViewModel( KnownMonikers.Overridden, CreateTextBlock(tooltipTextForAbstractFoo), tooltipTextForAbstractFoo, 1, targetForAbsFoo)}, {7, New InheritanceMarginGlyphViewModel( KnownMonikers.Overriding, CreateTextBlock(tooltipTextForBar), tooltipTextForBar, 1, targetForBar)}, {9, New InheritanceMarginGlyphViewModel( KnownMonikers.Overriding, CreateTextBlock(tooltipTextForOverrideFoo), tooltipTextForOverrideFoo, 1, targetForOverrideFoo)}}) End Function <WpfFact> Public Function TestInterfaceImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar1 { } public interface IBar2 : IBar1 { } public interface IBar3 : IBar2 { } " Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim targetForIBar1 = ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("IBar2", KnownMonikers.InterfacePublic, "IBar2", Nothing), New TargetMenuItemViewModel("IBar3", KnownMonikers.InterfacePublic, "IBar3", Nothing)) Dim tooltipTextForIBar2 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar2") Dim targetForIBar2 = ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfacePublic, "IBar1", Nothing), New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("IBar3", KnownMonikers.InterfacePublic, "IBar3", Nothing)) Dim tooltipTextForIBar3 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar3") Dim targetForIBar3 = ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, ServicesVSResources.Inherited_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfacePublic, "IBar1", Nothing), New TargetMenuItemViewModel("IBar2", KnownMonikers.InterfacePublic, "IBar2", Nothing)).CastArray(Of MenuItemViewModel) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From { {2, New InheritanceMarginGlyphViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar1), tooltipTextForIBar1, 1, targetForIBar1)}, {3, New InheritanceMarginGlyphViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForIBar2), tooltipTextForIBar2, 1, targetForIBar2)}, {4, New InheritanceMarginGlyphViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForIBar3), tooltipTextForIBar3, 1, targetForIBar3)}}) End Function <WpfFact> Public Function TestMutipleMemberOnSameline() As Task Dim markup = " using System; interface IBar1 { public event EventHandler e1, e2; } public class BarSample : IBar1 { public virtual event EventHandler e1, e2; }" Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim targetForIBar1 = ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_types, KnownMonikers.Implemented, ServicesVSResources.Implementing_types), New TargetMenuItemViewModel("BarSample", KnownMonikers.ClassPublic, "BarSample", Nothing)) Dim tooltipTextForE1AndE2InInterface = ServicesVSResources.Multiple_members_are_inherited Dim targetForE1AndE2InInterface = ImmutableArray.Create(Of MenuItemViewModel)( New MemberMenuItemViewModel("event EventHandler IBar1.e1", KnownMonikers.EventPublic, "event EventHandler IBar1.e1", ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members), New TargetMenuItemViewModel("BarSample.e1", KnownMonikers.EventPublic, "BarSample.e1", Nothing))), New MemberMenuItemViewModel("event EventHandler IBar1.e2", KnownMonikers.EventPublic, "event EventHandler IBar1.e2", ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implementing_members, KnownMonikers.Implemented, ServicesVSResources.Implementing_members), New TargetMenuItemViewModel("BarSample.e2", KnownMonikers.EventPublic, "BarSample.e2", Nothing)))) Dim tooltipTextForBarSample = String.Format(ServicesVSResources._0_is_inherited, "class BarSample") Dim targetForBarSample = ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, ServicesVSResources.Implemented_interfaces), New TargetMenuItemViewModel("IBar1", KnownMonikers.InterfaceInternal, "IBar1", Nothing)) Dim tooltipTextForE1AndE2InBarSample = ServicesVSResources.Multiple_members_are_inherited Dim targetForE1AndE2InInBarSample = ImmutableArray.Create(Of MenuItemViewModel)( New MemberMenuItemViewModel("virtual event EventHandler BarSample.e1", KnownMonikers.EventPublic, "virtual event EventHandler BarSample.e1", ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members), New TargetMenuItemViewModel("IBar1.e1", KnownMonikers.EventPublic, "IBar1.e1", Nothing)).CastArray(Of MenuItemViewModel)), New MemberMenuItemViewModel("virtual event EventHandler BarSample.e2", KnownMonikers.EventPublic, "virtual event EventHandler BarSample.e2", ImmutableArray.Create(Of MenuItemViewModel)( New HeaderMenuItemViewModel(ServicesVSResources.Implemented_members, KnownMonikers.Implementing, ServicesVSResources.Implemented_members), New TargetMenuItemViewModel("IBar1.e2", KnownMonikers.EventPublic, "IBar1.e2", Nothing)).CastArray(Of MenuItemViewModel))) _ .CastArray(Of MenuItemViewModel) Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, InheritanceMarginGlyphViewModel) From { {3, New InheritanceMarginGlyphViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForIBar1), tooltipTextForIBar1, 1, targetForIBar1)}, {5, New InheritanceMarginGlyphViewModel( KnownMonikers.Implemented, CreateTextBlock(tooltipTextForE1AndE2InInterface), String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 5), 1, targetForE1AndE2InInterface)}, {8, New InheritanceMarginGlyphViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForBarSample), tooltipTextForBarSample, 1, targetForBarSample)}, {10, New InheritanceMarginGlyphViewModel( KnownMonikers.Implementing, CreateTextBlock(tooltipTextForE1AndE2InBarSample), String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 10), 1, targetForE1AndE2InInBarSample)}}) 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 System.Windows Imports System.Windows.Documents Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InheritanceMargin Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.Imaging.Interop Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin Imports Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph Imports Microsoft.VisualStudio.Text.Classification Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.InheritanceMargin <Trait(Traits.Feature, Traits.Features.InheritanceMargin)> <UseExportProvider> Public Class InheritanceMarginViewModelTests Private Shared s_defaultMargin As Thickness = New Thickness(4, 1, 4, 1) Private Shared s_indentMargin As Thickness = New Thickness(22, 1, 4, 1) Private Structure GlyphViewModelData Public ReadOnly Property ImageMoniker As ImageMoniker Public ReadOnly Property ToolTipText As String Public ReadOnly Property AutomationName As String Public ReadOnly Property ScaleFactor As Double Public ReadOnly Property MenuItems As MenuItemViewModelData() Public Sub New(imageMoniker As ImageMoniker, toolTipText As String, automationName As String, scaleFactor As Double, ParamArray menuItems() As MenuItemViewModelData) Me.ImageMoniker = imageMoniker Me.ToolTipText = toolTipText Me.AutomationName = automationName Me.ScaleFactor = scaleFactor Me.MenuItems = menuItems End Sub End Structure Private Structure MenuItemViewModelData Public ReadOnly Property AutomationName As String Public ReadOnly Property DisplayContent As String Public ReadOnly Property ImageMoniker As ImageMoniker Public ReadOnly Property ViewModelType As Type Public ReadOnly Property MenuItems As MenuItemViewModelData() Public Sub New(automationName As String, displayContent As String, imageMoniker As ImageMoniker, viewModelType As Type, ParamArray menuItems() As MenuItemViewModelData) Me.AutomationName = automationName Me.DisplayContent = displayContent Me.ImageMoniker = imageMoniker Me.ViewModelType = viewModelType Me.MenuItems = menuItems End Sub End Structure Private Shared Async Function VerifyAsync(markup As String, languageName As String, expectedViewModels As Dictionary(Of Integer, GlyphViewModelData)) As Task ' Add an lf before the document so that the line number starts ' with 1, which meets the line number in the editor (but in fact all things start from 0) Dim workspaceFile = <Workspace> <Project Language=<%= languageName %> CommonReferences="true"> <Document><%= vbLf %> <%= markup.Replace(vbCrLf, vbLf) %> </Document> </Project> </Workspace> Dim cancellationToken As CancellationToken = CancellationToken.None Using workspace = TestWorkspace.Create(workspaceFile) Dim testDocument = workspace.Documents.Single() Dim document = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim service = document.GetRequiredLanguageService(Of IInheritanceMarginService) Dim classificationTypeMap = workspace.ExportProvider.GetExportedValue(Of ClassificationTypeMap) Dim classificationFormatMap = workspace.ExportProvider.GetExportedValue(Of IClassificationFormatMapService) ' For these tests, we need to be on UI thread, so don't call ConfigureAwait(False) Dim root = Await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(True) Dim inheritanceItems = Await service.GetInheritanceMemberItemsAsync(document, root.FullSpan, cancellationToken).ConfigureAwait(True) Dim acutalLineToTagDictionary = inheritanceItems.GroupBy(Function(item) item.LineNumber) _ .ToDictionary(Function(grouping) grouping.Key, Function(grouping) Dim lineNumber = grouping.Key Dim items = grouping.Select(Function(g) g).ToImmutableArray() Return New InheritanceMarginTag(workspace, lineNumber, items) End Function) Assert.Equal(expectedViewModels.Count, acutalLineToTagDictionary.Count) For Each kvp In expectedViewModels Dim lineNumber = kvp.Key Dim expectedViewModel = kvp.Value Assert.True(acutalLineToTagDictionary.ContainsKey(lineNumber)) Dim acutalTag = acutalLineToTagDictionary(lineNumber) ' Editor TestView zoom level is 100 based. Dim actualViewModel = InheritanceMarginGlyphViewModel.Create( classificationTypeMap, classificationFormatMap.GetClassificationFormatMap("tooltip"), acutalTag, 100) VerifyTwoViewModelAreSame(expectedViewModel, actualViewModel) Next End Using End Function Private Shared Sub VerifyTwoViewModelAreSame(expected As GlyphViewModelData, actual As InheritanceMarginGlyphViewModel) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Dim actualTextGetFromTextBlock = actual.ToolTipTextBlock.Inlines _ .OfType(Of Run).Select(Function(run) run.Text) _ .Aggregate(Function(text1, text2) text1 + text2) ' When the text block is created, a unicode 'left to right' would be inserted between the space. ' Make sure it is removed. Dim leftToRightMarker = Char.ConvertFromUtf32(&H200E) Dim actualText = actualTextGetFromTextBlock.Replace(leftToRightMarker, String.Empty) Assert.Equal(expected.ToolTipText, actualText) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.MenuItems.Length, actual.MenuItemViewModels.Length) Assert.Equal(expected.ScaleFactor, actual.ScaleFactor) For i = 0 To expected.MenuItems.Length - 1 Dim expectedMenuItem = expected.MenuItems(i) Dim actualMenuItem = actual.MenuItemViewModels(i) VerifyMenuItem(expectedMenuItem, actualMenuItem) Next End Sub Private Shared Sub VerifyMenuItem(expected As MenuItemViewModelData, actual As MenuItemViewModel) Assert.Equal(expected.AutomationName, actual.AutomationName) Assert.Equal(expected.DisplayContent, actual.DisplayContent) Assert.Equal(expected.ImageMoniker, actual.ImageMoniker) Assert.IsType(expected.ViewModelType, actual) If expected.ViewModelType = GetType(MemberMenuItemViewModel) Then Dim acutalMemberMenuItem = CType(actual, MemberMenuItemViewModel) Assert.Equal(expected.MenuItems.Length, acutalMemberMenuItem.Targets.Length) For i = 0 To expected.MenuItems.Length - 1 VerifyMenuItem(expected.MenuItems(i), acutalMemberMenuItem.Targets(i)) Next End If End Sub <WpfFact> Public Function TestClassImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar { } public class Bar : IBar { }" Dim tooltipTextForIBar = String.Format(ServicesVSResources._0_is_inherited, "interface IBar") Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From { {2, New GlyphViewModelData( KnownMonikers.Implemented, tooltipTextForIBar, tooltipTextForIBar, 1, New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("Bar", "Bar", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))}, {5, New GlyphViewModelData( KnownMonikers.Implementing, tooltipTextForBar, tooltipTextForBar, 1, New MenuItemViewModelData(ServicesVSResources.Implemented_interfaces, ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar", "IBar", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))}}) End Function <WpfFact> Public Function TestClassOverridesAbstractClassRelationship() As Task Dim markup = " public abstract class AbsBar { public abstract void Foo(); } public class Bar : AbsBar { public override void Foo(); }" Dim tooltipTextForAbsBar = String.Format(ServicesVSResources._0_is_inherited, "class AbsBar") Dim tooltipTextForAbstractFoo = String.Format(ServicesVSResources._0_is_inherited, "abstract void AbsBar.Foo()") Dim tooltipTextForBar = String.Format(ServicesVSResources._0_is_inherited, "class Bar") Dim tooltipTextForOverrideFoo = String.Format(ServicesVSResources._0_is_inherited, "override void Bar.Foo()") Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From { {2, New GlyphViewModelData( KnownMonikers.Overridden, tooltipTextForAbsBar, tooltipTextForAbsBar, 1, New MenuItemViewModelData(ServicesVSResources.Derived_types, ServicesVSResources.Derived_types, KnownMonikers.Overridden, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("Bar", "Bar", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))}, {4, New GlyphViewModelData( KnownMonikers.Overridden, tooltipTextForAbstractFoo, tooltipTextForAbstractFoo, 1, New MenuItemViewModelData(ServicesVSResources.Overriding_members, ServicesVSResources.Overriding_members, KnownMonikers.Overridden, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("Bar.Foo", "Bar.Foo", KnownMonikers.MethodPublic, GetType(TargetMenuItemViewModel)))}, {7, New GlyphViewModelData( KnownMonikers.Overriding, tooltipTextForBar, tooltipTextForBar, 1, New MenuItemViewModelData(ServicesVSResources.Base_Types, ServicesVSResources.Base_Types, KnownMonikers.Overriding, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("AbsBar", "AbsBar", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))}, {9, New GlyphViewModelData( KnownMonikers.Overriding, tooltipTextForOverrideFoo, tooltipTextForOverrideFoo, 1, New MenuItemViewModelData(ServicesVSResources.Overridden_members, ServicesVSResources.Overridden_members, KnownMonikers.Overriding, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("AbsBar.Foo", "AbsBar.Foo", KnownMonikers.MethodPublic, GetType(TargetMenuItemViewModel)))}}) End Function <WpfFact> Public Function TestInterfaceImplementsInterfaceRelationship() As Task Dim markup = " public interface IBar1 { } public interface IBar2 : IBar1 { } public interface IBar3 : IBar2 { } " Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim tooltipTextForIBar2 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar2") Dim tooltipTextForIBar3 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar3") Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From { {2, New GlyphViewModelData( KnownMonikers.Implemented, tooltipTextForIBar1, tooltipTextForIBar1, 1, New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar2", "IBar2", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)), New MenuItemViewModelData("IBar3", "IBar3", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))}, {3, New GlyphViewModelData( KnownMonikers.Implementing, tooltipTextForIBar2, tooltipTextForIBar2, 1, New MenuItemViewModelData(ServicesVSResources.Inherited_interfaces, ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar1", "IBar1", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)), New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar3", "IBar3", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))}, {4, New GlyphViewModelData( KnownMonikers.Implementing, tooltipTextForIBar3, tooltipTextForIBar3, 1, New MenuItemViewModelData(ServicesVSResources.Inherited_interfaces, ServicesVSResources.Inherited_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar1", "IBar1", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)), New MenuItemViewModelData("IBar2", "IBar2", KnownMonikers.InterfacePublic, GetType(TargetMenuItemViewModel)))}}) End Function <WpfFact> Public Function TestMutipleMemberOnSameline() As Task Dim markup = " using System; interface IBar1 { public event EventHandler e1, e2; } public class BarSample : IBar1 { public virtual event EventHandler e1, e2; }" Dim tooltipTextForIBar1 = String.Format(ServicesVSResources._0_is_inherited, "interface IBar1") Dim tooltipTextForE1AndE2InInterface = ServicesVSResources.Multiple_members_are_inherited Dim tooltipTextForBarSample = String.Format(ServicesVSResources._0_is_inherited, "class BarSample") Dim tooltipTextForE1AndE2InBarSample = ServicesVSResources.Multiple_members_are_inherited Return VerifyAsync(markup, LanguageNames.CSharp, New Dictionary(Of Integer, GlyphViewModelData) From { {3, New GlyphViewModelData( KnownMonikers.Implemented, tooltipTextForIBar1, tooltipTextForIBar1, 1, New MenuItemViewModelData(ServicesVSResources.Implementing_types, ServicesVSResources.Implementing_types, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("BarSample", "BarSample", KnownMonikers.ClassPublic, GetType(TargetMenuItemViewModel)))}, {5, New GlyphViewModelData( KnownMonikers.Implemented, tooltipTextForE1AndE2InInterface, String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 5), 1, New MenuItemViewModelData("event EventHandler IBar1.e1", "event EventHandler IBar1.e1", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel), New MenuItemViewModelData(ServicesVSResources.Implementing_members, ServicesVSResources.Implementing_members, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("BarSample.e1", "BarSample.e1", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))), New MenuItemViewModelData("event EventHandler IBar1.e2", "event EventHandler IBar1.e2", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel), New MenuItemViewModelData(ServicesVSResources.Implementing_members, ServicesVSResources.Implementing_members, KnownMonikers.Implemented, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("BarSample.e2", "BarSample.e2", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))))}, {8, New GlyphViewModelData( KnownMonikers.Implementing, tooltipTextForBarSample, tooltipTextForBarSample, 1, New MenuItemViewModelData(ServicesVSResources.Implemented_interfaces, ServicesVSResources.Implemented_interfaces, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar1", "IBar1", KnownMonikers.InterfaceInternal, GetType(TargetMenuItemViewModel)))}, {10, New GlyphViewModelData( KnownMonikers.Implementing, tooltipTextForE1AndE2InBarSample, String.Format(ServicesVSResources.Multiple_members_are_inherited_on_line_0, 10), 1, New MenuItemViewModelData("virtual event EventHandler BarSample.e1", "virtual event EventHandler BarSample.e1", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel), New MenuItemViewModelData(ServicesVSResources.Implemented_members, ServicesVSResources.Implemented_members, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar1.e1", "IBar1.e1", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))), New MenuItemViewModelData("virtual event EventHandler BarSample.e2", "virtual event EventHandler BarSample.e2", KnownMonikers.EventPublic, GetType(MemberMenuItemViewModel), New MenuItemViewModelData(ServicesVSResources.Implemented_members, ServicesVSResources.Implemented_members, KnownMonikers.Implementing, GetType(HeaderMenuItemViewModel)), New MenuItemViewModelData("IBar1.e2", "IBar1.e2", KnownMonikers.EventPublic, GetType(TargetMenuItemViewModel))))}}) End Function End Class End Namespace
1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/IfKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public IfKeywordRecommender() : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsPreProcessorKeywordContext || context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public IfKeywordRecommender() : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsPreProcessorKeywordContext || context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/Core/Portable/PEWriter/Miscellaneous.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// A container for static helper methods that are used for manipulating and computing iterators. /// </summary> internal static class IteratorHelper { /// <summary> /// True if the given enumerable is not null and contains at least one element. /// </summary> public static bool EnumerableIsNotEmpty<T>([NotNullWhen(returnValue: true)] IEnumerable<T>? enumerable) { if (enumerable == null) { return false; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return asIListT.Count != 0; } var asIList = enumerable as IList; if (asIList != null) { return asIList.Count != 0; } return enumerable.GetEnumerator().MoveNext(); } /// <summary> /// True if the given enumerable is null or contains no elements /// </summary> public static bool EnumerableIsEmpty<T>([NotNullWhen(returnValue: false)] IEnumerable<T>? enumerable) { return !EnumerableIsNotEmpty<T>(enumerable); } /// <summary> /// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0. /// </summary> public static uint EnumerableCount<T>(IEnumerable<T>? enumerable) { // ^ ensures result >= 0; if (enumerable == null) { return 0; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return (uint)asIListT.Count; } var asIList = enumerable as IList; if (asIList != null) { return (uint)asIList.Count; } uint result = 0; IEnumerator<T> enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { result++; } return result & 0x7FFFFFFF; } } /// <summary> /// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions. /// Each security attribute represents a serialized permission or permission set for a specified security action. /// The union of the security attributes with identical security action, define the permission set to which the security action applies. /// </summary> internal struct SecurityAttribute { public DeclarativeSecurityAction Action { get; } public ICustomAttribute Attribute { get; } public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute) { Action = action; Attribute = attribute; } } /// <summary> /// Information about how values of managed types should be marshalled to and from unmanaged types. /// </summary> internal interface IMarshallingInformation { /// <summary> /// <see cref="ITypeReference"/> or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string). /// </summary> object GetCustomMarshaller(EmitContext context); /// <summary> /// An argument string (cookie) passed to the custom marshaller at run time. /// </summary> string CustomMarshallerRuntimeArgument { get; } /// <summary> /// The unmanaged element type of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> System.Runtime.InteropServices.UnmanagedType ElementType { get; } /// <summary> /// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object. /// -1 if it should be omitted from the marshal blob. /// </summary> int IidParameterIndex { get; } /// <summary> /// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type /// is decided at runtime. /// </summary> System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; } /// <summary> /// The number of elements in the fixed size portion of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> int NumberOfElements { get; } /// <summary> /// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array. /// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way. /// </summary> short ParamIndex { get; } /// <summary> /// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype. /// (The element type of a safe array is VARIANT. The "sub type" specifies the value of all of the tag fields (vt) of the element values. ) /// -1 if it should be omitted from the marshal blob. /// </summary> VarEnum SafeArrayElementSubtype { get; } /// <summary> /// A reference to the user defined type to which the variant values of all elements of the safe array must belong. /// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD. /// The "user defined sub type" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.) /// </summary> ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context); } /// <summary> /// Implemented by any entity that has a name. /// </summary> internal interface INamedEntity { /// <summary> /// The name of the entity. /// </summary> string? Name { get; } } /// <summary> /// The name of the entity depends on other metadata (tokens, signatures) originated from /// PeWriter. /// </summary> internal interface IContextualNamedEntity : INamedEntity { /// <summary> /// Method must be called before calling INamedEntity.Name. /// </summary> void AssociateWithMetadataWriter(MetadataWriter metadataWriter); } /// <summary> /// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition. /// Provides a way to determine the position where the entity appears in the parameter list. /// </summary> internal interface IParameterListEntry { /// <summary> /// The position in the parameter list where this instance can be found. /// </summary> ushort Index { get; } } /// <summary> /// Information that describes how a method from the underlying Platform is to be invoked. /// </summary> internal interface IPlatformInvokeInformation { /// <summary> /// Module providing the method/field. /// </summary> string? ModuleName { get; } /// <summary> /// Name of the method providing the implementation. /// </summary> string? EntryPointName { get; } /// <summary> /// Flags that determine marshalling behavior. /// </summary> MethodImportAttributes Flags { get; } } internal class ResourceSection { internal ResourceSection(byte[] sectionBytes, uint[] relocations) { RoslynDebug.Assert(sectionBytes != null); RoslynDebug.Assert(relocations != null); SectionBytes = sectionBytes; Relocations = relocations; } internal readonly byte[] SectionBytes; //This is the offset into SectionBytes that should be modified. //It should have the section's RVA added to it. internal readonly uint[] Relocations; } /// <summary> /// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file. /// See the Win32 UpdateResource method for more details. /// </summary> internal interface IWin32Resource { /// <summary> /// A string that identifies what type of resource this is. Only valid if this.TypeId &lt; 0. /// </summary> string TypeName { get; // ^ requires this.TypeId < 0; } /// <summary> /// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead. /// </summary> int TypeId { get; } /// <summary> /// The name of the resource. Only valid if this.Id &lt; 0. /// </summary> string Name { get; // ^ requires this.Id < 0; } /// <summary> /// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead. /// </summary> int Id { get; } /// <summary> /// The language for which this resource is appropriate. /// </summary> uint LanguageId { get; } /// <summary> /// The code page for which this resource is appropriate. /// </summary> uint CodePage { get; } /// <summary> /// The data of the resource. /// </summary> IEnumerable<byte> Data { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { /// <summary> /// A container for static helper methods that are used for manipulating and computing iterators. /// </summary> internal static class IteratorHelper { /// <summary> /// True if the given enumerable is not null and contains at least one element. /// </summary> public static bool EnumerableIsNotEmpty<T>([NotNullWhen(returnValue: true)] IEnumerable<T>? enumerable) { if (enumerable == null) { return false; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return asIListT.Count != 0; } var asIList = enumerable as IList; if (asIList != null) { return asIList.Count != 0; } return enumerable.GetEnumerator().MoveNext(); } /// <summary> /// True if the given enumerable is null or contains no elements /// </summary> public static bool EnumerableIsEmpty<T>([NotNullWhen(returnValue: false)] IEnumerable<T>? enumerable) { return !EnumerableIsNotEmpty<T>(enumerable); } /// <summary> /// Returns the number of elements in the given enumerable. A null enumerable is allowed and results in 0. /// </summary> public static uint EnumerableCount<T>(IEnumerable<T>? enumerable) { // ^ ensures result >= 0; if (enumerable == null) { return 0; } var asIListT = enumerable as IList<T>; if (asIListT != null) { return (uint)asIListT.Count; } var asIList = enumerable as IList; if (asIList != null) { return (uint)asIList.Count; } uint result = 0; IEnumerator<T> enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { result++; } return result & 0x7FFFFFFF; } } /// <summary> /// A declarative specification of a security action applied to a set of permissions. Used by the CLR loader to enforce security restrictions. /// Each security attribute represents a serialized permission or permission set for a specified security action. /// The union of the security attributes with identical security action, define the permission set to which the security action applies. /// </summary> internal struct SecurityAttribute { public DeclarativeSecurityAction Action { get; } public ICustomAttribute Attribute { get; } public SecurityAttribute(DeclarativeSecurityAction action, ICustomAttribute attribute) { Action = action; Attribute = attribute; } } /// <summary> /// Information about how values of managed types should be marshalled to and from unmanaged types. /// </summary> internal interface IMarshallingInformation { /// <summary> /// <see cref="ITypeReference"/> or a string (usually a fully-qualified type name of a type implementing the custom marshaller, but Dev11 allows any string). /// </summary> object GetCustomMarshaller(EmitContext context); /// <summary> /// An argument string (cookie) passed to the custom marshaller at run time. /// </summary> string CustomMarshallerRuntimeArgument { get; } /// <summary> /// The unmanaged element type of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> System.Runtime.InteropServices.UnmanagedType ElementType { get; } /// <summary> /// Specifies the index of the parameter that contains the value of the Interface Identifier (IID) of the marshalled object. /// -1 if it should be omitted from the marshal blob. /// </summary> int IidParameterIndex { get; } /// <summary> /// The unmanaged type to which the managed type will be marshalled. This can be UnmanagedType.CustomMarshaler, in which case the unmanaged type /// is decided at runtime. /// </summary> System.Runtime.InteropServices.UnmanagedType UnmanagedType { get; } /// <summary> /// The number of elements in the fixed size portion of the unmanaged array. /// -1 if it should be omitted from the marshal blob. /// </summary> int NumberOfElements { get; } /// <summary> /// The zero based index of the parameter in the unmanaged method that contains the number of elements in the variable portion of unmanaged array. /// If -1, the variable portion is of size zero, or the caller conveys the size of the variable portion of the array to the unmanaged method in some other way. /// </summary> short ParamIndex { get; } /// <summary> /// The type to which the variant values of all elements of the safe array must belong. See also SafeArrayElementUserDefinedSubtype. /// (The element type of a safe array is VARIANT. The "sub type" specifies the value of all of the tag fields (vt) of the element values. ) /// -1 if it should be omitted from the marshal blob. /// </summary> VarEnum SafeArrayElementSubtype { get; } /// <summary> /// A reference to the user defined type to which the variant values of all elements of the safe array must belong. /// (The element type of a safe array is VARIANT. The tag fields will all be either VT_DISPATCH or VT_UNKNOWN or VT_RECORD. /// The "user defined sub type" specifies the type of value the ppdispVal/ppunkVal/pvRecord fields of the element values may point to.) /// </summary> ITypeReference GetSafeArrayElementUserDefinedSubtype(EmitContext context); } /// <summary> /// Implemented by any entity that has a name. /// </summary> internal interface INamedEntity { /// <summary> /// The name of the entity. /// </summary> string? Name { get; } } /// <summary> /// The name of the entity depends on other metadata (tokens, signatures) originated from /// PeWriter. /// </summary> internal interface IContextualNamedEntity : INamedEntity { /// <summary> /// Method must be called before calling INamedEntity.Name. /// </summary> void AssociateWithMetadataWriter(MetadataWriter metadataWriter); } /// <summary> /// Implemented by an entity that is always a member of a particular parameter list, such as an IParameterDefinition. /// Provides a way to determine the position where the entity appears in the parameter list. /// </summary> internal interface IParameterListEntry { /// <summary> /// The position in the parameter list where this instance can be found. /// </summary> ushort Index { get; } } /// <summary> /// Information that describes how a method from the underlying Platform is to be invoked. /// </summary> internal interface IPlatformInvokeInformation { /// <summary> /// Module providing the method/field. /// </summary> string? ModuleName { get; } /// <summary> /// Name of the method providing the implementation. /// </summary> string? EntryPointName { get; } /// <summary> /// Flags that determine marshalling behavior. /// </summary> MethodImportAttributes Flags { get; } } internal class ResourceSection { internal ResourceSection(byte[] sectionBytes, uint[] relocations) { RoslynDebug.Assert(sectionBytes != null); RoslynDebug.Assert(relocations != null); SectionBytes = sectionBytes; Relocations = relocations; } internal readonly byte[] SectionBytes; //This is the offset into SectionBytes that should be modified. //It should have the section's RVA added to it. internal readonly uint[] Relocations; } /// <summary> /// A resource file formatted according to Win32 API conventions and typically obtained from a Portable Executable (PE) file. /// See the Win32 UpdateResource method for more details. /// </summary> internal interface IWin32Resource { /// <summary> /// A string that identifies what type of resource this is. Only valid if this.TypeId &lt; 0. /// </summary> string TypeName { get; // ^ requires this.TypeId < 0; } /// <summary> /// An integer tag that identifies what type of resource this is. If the value is less than 0, this.TypeName should be used instead. /// </summary> int TypeId { get; } /// <summary> /// The name of the resource. Only valid if this.Id &lt; 0. /// </summary> string Name { get; // ^ requires this.Id < 0; } /// <summary> /// An integer tag that identifies this resource. If the value is less than 0, this.Name should be used instead. /// </summary> int Id { get; } /// <summary> /// The language for which this resource is appropriate. /// </summary> uint LanguageId { get; } /// <summary> /// The code page for which this resource is appropriate. /// </summary> uint CodePage { get; } /// <summary> /// The data of the resource. /// </summary> IEnumerable<byte> Data { get; } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/Core/CodeAnalysisTest/Collections/DebuggerAttributes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Diagnostics/DebuggerAttributes.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal class DebuggerAttributeInfo { public object Instance { get; } public IEnumerable<PropertyInfo> Properties { get; } public DebuggerAttributeInfo(object instance, IEnumerable<PropertyInfo> properties) { Instance = instance; Properties = properties; } } internal static class DebuggerAttributes { internal static object? GetFieldValue(object obj, string fieldName) { var fieldInfo = GetField(obj, fieldName) ?? throw new InvalidOperationException(); return fieldInfo.GetValue(obj); } internal static void InvokeDebuggerTypeProxyProperties(object obj) { DebuggerAttributeInfo info = ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); foreach (PropertyInfo pi in info.Properties) { pi.GetValue(info.Instance, null); } } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(object obj) { return ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, object obj) { return ValidateDebuggerTypeProxyProperties(type, type.GenericTypeArguments, obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, Type[] genericTypeArguments, object obj) { Type proxyType = GetProxyType(type, genericTypeArguments); // Create an instance of the proxy type, and make sure we can access all of the instance properties // on the type without exception object proxyInstance = Activator.CreateInstance(proxyType, obj) ?? throw ExceptionUtilities.Unreachable; IEnumerable<PropertyInfo> properties = GetDebuggerVisibleProperties(proxyType); return new DebuggerAttributeInfo(proxyInstance, properties); } public static DebuggerBrowsableState? GetDebuggerBrowsableState(MemberInfo info) { CustomAttributeData? debuggerBrowsableAttribute = info.CustomAttributes .SingleOrDefault(a => a.AttributeType == typeof(DebuggerBrowsableAttribute)); // Enums in attribute constructors are boxed as ints, so cast to int? first. return (DebuggerBrowsableState?)(int?)debuggerBrowsableAttribute?.ConstructorArguments.Single().Value; } public static IEnumerable<FieldInfo> GetDebuggerVisibleFields(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. IEnumerable<FieldInfo> visibleFields = debuggerAttributeType.GetFields() .Where(fi => fi.IsPublic && GetDebuggerBrowsableState(fi) != DebuggerBrowsableState.Never); return visibleFields; } public static IEnumerable<PropertyInfo> GetDebuggerVisibleProperties(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. GetGetMethod returns null if the getter is non-public. IEnumerable<PropertyInfo> visibleProperties = debuggerAttributeType.GetProperties() .Where(pi => pi.GetGetMethod() != null && GetDebuggerBrowsableState(pi) != DebuggerBrowsableState.Never); return visibleProperties; } public static object? GetProxyObject(object obj) => Activator.CreateInstance(GetProxyType(obj), obj); public static Type GetProxyType(object obj) => GetProxyType(obj.GetType()); public static Type GetProxyType(Type type) => GetProxyType(type, type.GenericTypeArguments); private static Type GetProxyType(Type type, Type[] genericTypeArguments) { // Get the DebuggerTypeProxyAttribute for obj var attrs = type.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerTypeProxyAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerTypeProxyAttribute on {type}."); } CustomAttributeData cad = attrs[0]; Type? proxyType = cad.ConstructorArguments[0].ArgumentType == typeof(Type) ? (Type?)cad.ConstructorArguments[0].Value : Type.GetType((string)cad.ConstructorArguments[0].Value!); if (proxyType is null) throw new InvalidOperationException("Expected a non-null proxy type"); if (genericTypeArguments.Length > 0) { proxyType = proxyType.MakeGenericType(genericTypeArguments); } return proxyType; } internal static string ValidateDebuggerDisplayReferences(object obj) { // Get the DebuggerDisplayAttribute for obj var objType = obj.GetType(); var attrs = objType.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerDisplayAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerDisplayAttribute on {objType}."); } var cad = attrs[0]; // Get the text of the DebuggerDisplayAttribute string attrText = (string?)cad.ConstructorArguments[0].Value ?? throw new InvalidOperationException("Expected a non-null text"); var segments = attrText.Split(new[] { '{', '}' }); if (segments.Length % 2 == 0) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} lacks a closing brace."); } if (segments.Length == 1) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} doesn't reference any expressions."); } var sb = new StringBuilder(); for (int i = 0; i < segments.Length; i += 2) { string literal = segments[i]; sb.Append(literal); if (i + 1 < segments.Length) { string reference = segments[i + 1]; bool noQuotes = reference.EndsWith(",nq"); reference = reference.Replace(",nq", string.Empty); // Evaluate the reference. if (!TryEvaluateReference(obj, reference, out object? member)) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} contains the expression \"{reference}\"."); } string? memberString = GetDebuggerMemberString(member, noQuotes); sb.Append(memberString); } } return sb.ToString(); } private static string? GetDebuggerMemberString(object? member, bool noQuotes) { string? memberString = "null"; if (member != null) { memberString = member.ToString(); if (member is string) { if (!noQuotes) { memberString = '"' + memberString + '"'; } } else if (!IsPrimitiveType(member)) { memberString = '{' + memberString + '}'; } } return memberString; } private static bool IsPrimitiveType(object obj) => obj is byte || obj is sbyte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is float || obj is double; private static bool TryEvaluateReference(object obj, string reference, out object? member) { PropertyInfo? pi = GetProperty(obj, reference); if (pi != null) { member = pi.GetValue(obj); return true; } FieldInfo? fi = GetField(obj, reference); if (fi != null) { member = fi.GetValue(obj); return true; } member = null; return false; } private static FieldInfo? GetField(object obj, string fieldName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { FieldInfo? fi = t.GetTypeInfo().GetDeclaredField(fieldName); if (fi != null) { return fi; } } return null; } private static PropertyInfo? GetProperty(object obj, string propertyName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { PropertyInfo? pi = t.GetTypeInfo().GetDeclaredProperty(propertyName); if (pi != null) { return pi; } } 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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Diagnostics/DebuggerAttributes.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal class DebuggerAttributeInfo { public object Instance { get; } public IEnumerable<PropertyInfo> Properties { get; } public DebuggerAttributeInfo(object instance, IEnumerable<PropertyInfo> properties) { Instance = instance; Properties = properties; } } internal static class DebuggerAttributes { internal static object? GetFieldValue(object obj, string fieldName) { var fieldInfo = GetField(obj, fieldName) ?? throw new InvalidOperationException(); return fieldInfo.GetValue(obj); } internal static void InvokeDebuggerTypeProxyProperties(object obj) { DebuggerAttributeInfo info = ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); foreach (PropertyInfo pi in info.Properties) { pi.GetValue(info.Instance, null); } } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(object obj) { return ValidateDebuggerTypeProxyProperties(obj.GetType(), obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, object obj) { return ValidateDebuggerTypeProxyProperties(type, type.GenericTypeArguments, obj); } internal static DebuggerAttributeInfo ValidateDebuggerTypeProxyProperties(Type type, Type[] genericTypeArguments, object obj) { Type proxyType = GetProxyType(type, genericTypeArguments); // Create an instance of the proxy type, and make sure we can access all of the instance properties // on the type without exception object proxyInstance = Activator.CreateInstance(proxyType, obj) ?? throw ExceptionUtilities.Unreachable; IEnumerable<PropertyInfo> properties = GetDebuggerVisibleProperties(proxyType); return new DebuggerAttributeInfo(proxyInstance, properties); } public static DebuggerBrowsableState? GetDebuggerBrowsableState(MemberInfo info) { CustomAttributeData? debuggerBrowsableAttribute = info.CustomAttributes .SingleOrDefault(a => a.AttributeType == typeof(DebuggerBrowsableAttribute)); // Enums in attribute constructors are boxed as ints, so cast to int? first. return (DebuggerBrowsableState?)(int?)debuggerBrowsableAttribute?.ConstructorArguments.Single().Value; } public static IEnumerable<FieldInfo> GetDebuggerVisibleFields(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. IEnumerable<FieldInfo> visibleFields = debuggerAttributeType.GetFields() .Where(fi => fi.IsPublic && GetDebuggerBrowsableState(fi) != DebuggerBrowsableState.Never); return visibleFields; } public static IEnumerable<PropertyInfo> GetDebuggerVisibleProperties(Type debuggerAttributeType) { // The debugger doesn't evaluate non-public members of type proxies. GetGetMethod returns null if the getter is non-public. IEnumerable<PropertyInfo> visibleProperties = debuggerAttributeType.GetProperties() .Where(pi => pi.GetGetMethod() != null && GetDebuggerBrowsableState(pi) != DebuggerBrowsableState.Never); return visibleProperties; } public static object? GetProxyObject(object obj) => Activator.CreateInstance(GetProxyType(obj), obj); public static Type GetProxyType(object obj) => GetProxyType(obj.GetType()); public static Type GetProxyType(Type type) => GetProxyType(type, type.GenericTypeArguments); private static Type GetProxyType(Type type, Type[] genericTypeArguments) { // Get the DebuggerTypeProxyAttribute for obj var attrs = type.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerTypeProxyAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerTypeProxyAttribute on {type}."); } CustomAttributeData cad = attrs[0]; Type? proxyType = cad.ConstructorArguments[0].ArgumentType == typeof(Type) ? (Type?)cad.ConstructorArguments[0].Value : Type.GetType((string)cad.ConstructorArguments[0].Value!); if (proxyType is null) throw new InvalidOperationException("Expected a non-null proxy type"); if (genericTypeArguments.Length > 0) { proxyType = proxyType.MakeGenericType(genericTypeArguments); } return proxyType; } internal static string ValidateDebuggerDisplayReferences(object obj) { // Get the DebuggerDisplayAttribute for obj var objType = obj.GetType(); var attrs = objType.GetTypeInfo().CustomAttributes .Where(a => a.AttributeType == typeof(DebuggerDisplayAttribute)) .ToArray(); if (attrs.Length != 1) { throw new InvalidOperationException($"Expected one DebuggerDisplayAttribute on {objType}."); } var cad = attrs[0]; // Get the text of the DebuggerDisplayAttribute string attrText = (string?)cad.ConstructorArguments[0].Value ?? throw new InvalidOperationException("Expected a non-null text"); var segments = attrText.Split(new[] { '{', '}' }); if (segments.Length % 2 == 0) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} lacks a closing brace."); } if (segments.Length == 1) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} doesn't reference any expressions."); } var sb = new StringBuilder(); for (int i = 0; i < segments.Length; i += 2) { string literal = segments[i]; sb.Append(literal); if (i + 1 < segments.Length) { string reference = segments[i + 1]; bool noQuotes = reference.EndsWith(",nq"); reference = reference.Replace(",nq", string.Empty); // Evaluate the reference. if (!TryEvaluateReference(obj, reference, out object? member)) { throw new InvalidOperationException($"The DebuggerDisplayAttribute for {objType} contains the expression \"{reference}\"."); } string? memberString = GetDebuggerMemberString(member, noQuotes); sb.Append(memberString); } } return sb.ToString(); } private static string? GetDebuggerMemberString(object? member, bool noQuotes) { string? memberString = "null"; if (member != null) { memberString = member.ToString(); if (member is string) { if (!noQuotes) { memberString = '"' + memberString + '"'; } } else if (!IsPrimitiveType(member)) { memberString = '{' + memberString + '}'; } } return memberString; } private static bool IsPrimitiveType(object obj) => obj is byte || obj is sbyte || obj is short || obj is ushort || obj is int || obj is uint || obj is long || obj is ulong || obj is float || obj is double; private static bool TryEvaluateReference(object obj, string reference, out object? member) { PropertyInfo? pi = GetProperty(obj, reference); if (pi != null) { member = pi.GetValue(obj); return true; } FieldInfo? fi = GetField(obj, reference); if (fi != null) { member = fi.GetValue(obj); return true; } member = null; return false; } private static FieldInfo? GetField(object obj, string fieldName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { FieldInfo? fi = t.GetTypeInfo().GetDeclaredField(fieldName); if (fi != null) { return fi; } } return null; } private static PropertyInfo? GetProperty(object obj, string propertyName) { for (Type? t = obj.GetType(); t != null; t = t.GetTypeInfo().BaseType) { PropertyInfo? pi = t.GetTypeInfo().GetDeclaredProperty(propertyName); if (pi != null) { return pi; } } return null; } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/CSharp/Portable/ExtractMethod/CSharpSyntaxTriviaServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxTriviaServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => CSharpSyntaxTriviaService.Instance; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxTriviaServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => CSharpSyntaxTriviaService.Instance; } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/VisualStudio/Core/Impl/CodeModel/ProjectCodeModelFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ComponentModel.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { [Export(typeof(IProjectCodeModelFactory))] [Export(typeof(ProjectCodeModelFactory))] internal sealed class ProjectCodeModelFactory : ForegroundThreadAffinitizedObject, IProjectCodeModelFactory { private readonly ConcurrentDictionary<ProjectId, ProjectCodeModel> _projectCodeModels = new ConcurrentDictionary<ProjectId, ProjectCodeModel>(); private readonly VisualStudioWorkspace _visualStudioWorkspace; private readonly IServiceProvider _serviceProvider; private readonly IThreadingContext _threadingContext; private readonly AsyncBatchingWorkQueue<DocumentId> _documentsToFireEventsFor; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ProjectCodeModelFactory( VisualStudioWorkspace visualStudioWorkspace, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, assertIsForeground: false) { _visualStudioWorkspace = visualStudioWorkspace; _serviceProvider = serviceProvider; _threadingContext = threadingContext; Listener = listenerProvider.GetListener(FeatureAttribute.CodeModel); // Queue up notifications we hear about docs changing. that way we don't have to fire events multiple times // for the same documents. Once enough time has passed, take the documents that were changed and run // through them, firing their latest events. _documentsToFireEventsFor = new AsyncBatchingWorkQueue<DocumentId>( InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan, ProcessNextDocumentBatchAsync, // We only care about unique doc-ids, so pass in this comparer to collapse streams of changes for a // single document down to one notification. EqualityComparer<DocumentId>.Default, Listener, threadingContext.DisposalToken); _visualStudioWorkspace.WorkspaceChanged += OnWorkspaceChanged; } internal IAsynchronousOperationListener Listener { get; } private async ValueTask ProcessNextDocumentBatchAsync( ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { // This logic preserves the previous behavior we had with IForegroundNotificationService. // Specifically, we don't run on the UI thread for more than 15ms at a time. And once we // have, we wait 50ms before continuing. These constants are just what we defined from // legacy, and otherwise have no special meaning. const int MaxTimeSlice = 15; var delayBetweenProcessing = TimeSpan.FromMilliseconds(50); Debug.Assert(!_threadingContext.JoinableTaskContext.IsOnMainThread, "The following context switch is not expected to cause runtime overhead."); await TaskScheduler.Default; // Ensure MEF services used by the code model are initially obtained on a background thread. // This code avoids allocations where possible. // https://github.com/dotnet/roslyn/issues/54159 string? previousLanguage = null; foreach (var (_, projectState) in _visualStudioWorkspace.CurrentSolution.State.ProjectStates) { if (projectState.Language == previousLanguage) { // Avoid duplicate calls if the language did not change continue; } previousLanguage = projectState.Language; projectState.LanguageServices.GetService<ICodeModelService>(); projectState.LanguageServices.GetService<ISyntaxFactsService>(); projectState.LanguageServices.GetService<ICodeGenerationService>(); } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var stopwatch = SharedStopwatch.StartNew(); foreach (var documentId in documentIds) { FireEventsForDocument(documentId); // Keep firing events for this doc, as long as we haven't exceeded the max amount // of waiting time, and there's no user input that should take precedence. if (stopwatch.Elapsed.Ticks > MaxTimeSlice || IsInputPending()) { await this.Listener.Delay(delayBetweenProcessing, cancellationToken).ConfigureAwait(true); stopwatch = SharedStopwatch.StartNew(); } } return; void FireEventsForDocument(DocumentId documentId) { // If we've been asked to shutdown, don't bother reporting any more events. if (_threadingContext.DisposalToken.IsCancellationRequested) return; var projectCodeModel = this.TryGetProjectCodeModel(documentId.ProjectId); if (projectCodeModel == null) return; var filename = _visualStudioWorkspace.GetFilePath(documentId); if (filename == null) return; if (!projectCodeModel.TryGetCachedFileCodeModel(filename, out var fileCodeModelHandle)) return; var codeModel = fileCodeModelHandle.Object; codeModel.FireEvents(); return; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { // Events that can't change existing code model items. Can just ignore them. switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: return; case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.DocumentChanged: // Fast path when we know we affected a document that could have had code model elements in it. No // need to do a solution diff in this case. _documentsToFireEventsFor.AddWork(e.DocumentId!); return; } // Other type of event that could indicate a doc change/removal. Have to actually analyze the change to // determine what we should do here. var changes = e.OldSolution.GetChanges(e.NewSolution); foreach (var project in changes.GetRemovedProjects()) _documentsToFireEventsFor.AddWork(project.DocumentIds); foreach (var projectChange in changes.GetProjectChanges()) { _documentsToFireEventsFor.AddWork(projectChange.GetRemovedDocuments()); _documentsToFireEventsFor.AddWork(projectChange.GetChangedDocuments()); } } public IProjectCodeModel CreateProjectCodeModel(ProjectId id, ICodeModelInstanceFactory codeModelInstanceFactory) { var projectCodeModel = new ProjectCodeModel(_threadingContext, id, codeModelInstanceFactory, _visualStudioWorkspace, _serviceProvider, this); if (!_projectCodeModels.TryAdd(id, projectCodeModel)) { throw new InvalidOperationException($"A {nameof(IProjectCodeModel)} has already been created for project with ID {id}"); } return projectCodeModel; } public ProjectCodeModel GetProjectCodeModel(ProjectId id) { if (!_projectCodeModels.TryGetValue(id, out var projectCodeModel)) { throw new InvalidOperationException($"No {nameof(ProjectCodeModel)} exists for project with ID {id}"); } return projectCodeModel; } public IEnumerable<ProjectCodeModel> GetAllProjectCodeModels() => _projectCodeModels.Values; internal void OnProjectClosed(ProjectId projectId) => _projectCodeModels.TryRemove(projectId, out _); public ProjectCodeModel TryGetProjectCodeModel(ProjectId id) { _projectCodeModels.TryGetValue(id, out var projectCodeModel); return projectCodeModel; } public EnvDTE.FileCodeModel GetOrCreateFileCodeModel(ProjectId id, string filePath) => GetProjectCodeModel(id).GetOrCreateFileCodeModel(filePath).Handle; public void ScheduleDeferredCleanupTask(Action<CancellationToken> a) { _ = _threadingContext.RunWithShutdownBlockAsync(async cancellationToken => { await _threadingContext.JoinableTaskFactory.StartOnIdle( () => a(cancellationToken), VsTaskRunContext.UIThreadNormalPriority); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.ComponentModel.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { [Export(typeof(IProjectCodeModelFactory))] [Export(typeof(ProjectCodeModelFactory))] internal sealed class ProjectCodeModelFactory : ForegroundThreadAffinitizedObject, IProjectCodeModelFactory { private readonly ConcurrentDictionary<ProjectId, ProjectCodeModel> _projectCodeModels = new ConcurrentDictionary<ProjectId, ProjectCodeModel>(); private readonly VisualStudioWorkspace _visualStudioWorkspace; private readonly IServiceProvider _serviceProvider; private readonly IThreadingContext _threadingContext; private readonly AsyncBatchingWorkQueue<DocumentId> _documentsToFireEventsFor; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ProjectCodeModelFactory( VisualStudioWorkspace visualStudioWorkspace, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider, IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, assertIsForeground: false) { _visualStudioWorkspace = visualStudioWorkspace; _serviceProvider = serviceProvider; _threadingContext = threadingContext; Listener = listenerProvider.GetListener(FeatureAttribute.CodeModel); // Queue up notifications we hear about docs changing. that way we don't have to fire events multiple times // for the same documents. Once enough time has passed, take the documents that were changed and run // through them, firing their latest events. _documentsToFireEventsFor = new AsyncBatchingWorkQueue<DocumentId>( InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan, ProcessNextDocumentBatchAsync, // We only care about unique doc-ids, so pass in this comparer to collapse streams of changes for a // single document down to one notification. EqualityComparer<DocumentId>.Default, Listener, threadingContext.DisposalToken); _visualStudioWorkspace.WorkspaceChanged += OnWorkspaceChanged; } internal IAsynchronousOperationListener Listener { get; } private async ValueTask ProcessNextDocumentBatchAsync( ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { // This logic preserves the previous behavior we had with IForegroundNotificationService. // Specifically, we don't run on the UI thread for more than 15ms at a time. And once we // have, we wait 50ms before continuing. These constants are just what we defined from // legacy, and otherwise have no special meaning. const int MaxTimeSlice = 15; var delayBetweenProcessing = TimeSpan.FromMilliseconds(50); Debug.Assert(!_threadingContext.JoinableTaskContext.IsOnMainThread, "The following context switch is not expected to cause runtime overhead."); await TaskScheduler.Default; // Ensure MEF services used by the code model are initially obtained on a background thread. // This code avoids allocations where possible. // https://github.com/dotnet/roslyn/issues/54159 string? previousLanguage = null; foreach (var (_, projectState) in _visualStudioWorkspace.CurrentSolution.State.ProjectStates) { if (projectState.Language == previousLanguage) { // Avoid duplicate calls if the language did not change continue; } previousLanguage = projectState.Language; projectState.LanguageServices.GetService<ICodeModelService>(); projectState.LanguageServices.GetService<ISyntaxFactsService>(); projectState.LanguageServices.GetService<ICodeGenerationService>(); } await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var stopwatch = SharedStopwatch.StartNew(); foreach (var documentId in documentIds) { FireEventsForDocument(documentId); // Keep firing events for this doc, as long as we haven't exceeded the max amount // of waiting time, and there's no user input that should take precedence. if (stopwatch.Elapsed.Ticks > MaxTimeSlice || IsInputPending()) { await this.Listener.Delay(delayBetweenProcessing, cancellationToken).ConfigureAwait(true); stopwatch = SharedStopwatch.StartNew(); } } return; void FireEventsForDocument(DocumentId documentId) { // If we've been asked to shutdown, don't bother reporting any more events. if (_threadingContext.DisposalToken.IsCancellationRequested) return; var projectCodeModel = this.TryGetProjectCodeModel(documentId.ProjectId); if (projectCodeModel == null) return; var filename = _visualStudioWorkspace.GetFilePath(documentId); if (filename == null) return; if (!projectCodeModel.TryGetCachedFileCodeModel(filename, out var fileCodeModelHandle)) return; var codeModel = fileCodeModelHandle.Object; codeModel.FireEvents(); return; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { // Events that can't change existing code model items. Can just ignore them. switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentReloaded: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AnalyzerConfigDocumentAdded: case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved: case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded: case WorkspaceChangeKind.AnalyzerConfigDocumentChanged: return; case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.DocumentChanged: // Fast path when we know we affected a document that could have had code model elements in it. No // need to do a solution diff in this case. _documentsToFireEventsFor.AddWork(e.DocumentId!); return; } // Other type of event that could indicate a doc change/removal. Have to actually analyze the change to // determine what we should do here. var changes = e.OldSolution.GetChanges(e.NewSolution); foreach (var project in changes.GetRemovedProjects()) _documentsToFireEventsFor.AddWork(project.DocumentIds); foreach (var projectChange in changes.GetProjectChanges()) { _documentsToFireEventsFor.AddWork(projectChange.GetRemovedDocuments()); _documentsToFireEventsFor.AddWork(projectChange.GetChangedDocuments()); } } public IProjectCodeModel CreateProjectCodeModel(ProjectId id, ICodeModelInstanceFactory codeModelInstanceFactory) { var projectCodeModel = new ProjectCodeModel(_threadingContext, id, codeModelInstanceFactory, _visualStudioWorkspace, _serviceProvider, this); if (!_projectCodeModels.TryAdd(id, projectCodeModel)) { throw new InvalidOperationException($"A {nameof(IProjectCodeModel)} has already been created for project with ID {id}"); } return projectCodeModel; } public ProjectCodeModel GetProjectCodeModel(ProjectId id) { if (!_projectCodeModels.TryGetValue(id, out var projectCodeModel)) { throw new InvalidOperationException($"No {nameof(ProjectCodeModel)} exists for project with ID {id}"); } return projectCodeModel; } public IEnumerable<ProjectCodeModel> GetAllProjectCodeModels() => _projectCodeModels.Values; internal void OnProjectClosed(ProjectId projectId) => _projectCodeModels.TryRemove(projectId, out _); public ProjectCodeModel TryGetProjectCodeModel(ProjectId id) { _projectCodeModels.TryGetValue(id, out var projectCodeModel); return projectCodeModel; } public EnvDTE.FileCodeModel GetOrCreateFileCodeModel(ProjectId id, string filePath) => GetProjectCodeModel(id).GetOrCreateFileCodeModel(filePath).Handle; public void ScheduleDeferredCleanupTask(Action<CancellationToken> a) { _ = _threadingContext.RunWithShutdownBlockAsync(async cancellationToken => { await _threadingContext.JoinableTaskFactory.StartOnIdle( () => a(cancellationToken), VsTaskRunContext.UIThreadNormalPriority); }); } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/Core/Portable/Completion/CompletionRules.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Presentation and behavior rules for completion. /// </summary> public sealed class CompletionRules { /// <summary> /// True if the completion list should be dismissed if the user's typing causes it to filter /// and display no items. /// </summary> public bool DismissIfEmpty { get; } /// <summary> /// True if the list should be dismissed when the user deletes the last character in the span. /// </summary> public bool DismissIfLastCharacterDeleted { get; } /// <summary> /// The default set of typed characters that cause the selected item to be committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public ImmutableArray<char> DefaultCommitCharacters { get; } /// <summary> /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public EnterKeyRule DefaultEnterKeyRule { get; } /// <summary> /// The rule determining how snippets work. /// </summary> public SnippetsRule SnippetsRule { get; } private CompletionRules( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule, SnippetsRule snippetsRule) { DismissIfEmpty = dismissIfEmpty; DismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted; DefaultCommitCharacters = defaultCommitCharacters.NullToEmpty(); DefaultEnterKeyRule = defaultEnterKeyRule; SnippetsRule = snippetsRule; } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> public static CompletionRules Create( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule) { return Create(dismissIfEmpty, dismissIfLastCharacterDeleted, defaultCommitCharacters, defaultEnterKeyRule, SnippetsRule.Default); } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="snippetsRule">The rule that controls snippets behavior.</param> public static CompletionRules Create( bool dismissIfEmpty = false, bool dismissIfLastCharacterDeleted = false, ImmutableArray<char> defaultCommitCharacters = default, EnterKeyRule defaultEnterKeyRule = EnterKeyRule.Default, SnippetsRule snippetsRule = SnippetsRule.Default) { return new CompletionRules( dismissIfEmpty: dismissIfEmpty, dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted, defaultCommitCharacters: defaultCommitCharacters, defaultEnterKeyRule: defaultEnterKeyRule, snippetsRule: snippetsRule); } private CompletionRules With( Optional<bool> dismissIfEmpty = default, Optional<bool> dismissIfLastCharacterDeleted = default, Optional<ImmutableArray<char>> defaultCommitCharacters = default, Optional<EnterKeyRule> defaultEnterKeyRule = default, Optional<SnippetsRule> snippetsRule = default) { var newDismissIfEmpty = dismissIfEmpty.HasValue ? dismissIfEmpty.Value : DismissIfEmpty; var newDismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted.HasValue ? dismissIfLastCharacterDeleted.Value : DismissIfLastCharacterDeleted; var newDefaultCommitCharacters = defaultCommitCharacters.HasValue ? defaultCommitCharacters.Value : DefaultCommitCharacters; var newDefaultEnterKeyRule = defaultEnterKeyRule.HasValue ? defaultEnterKeyRule.Value : DefaultEnterKeyRule; var newSnippetsRule = snippetsRule.HasValue ? snippetsRule.Value : SnippetsRule; if (newDismissIfEmpty == DismissIfEmpty && newDismissIfLastCharacterDeleted == DismissIfLastCharacterDeleted && newDefaultCommitCharacters == DefaultCommitCharacters && newDefaultEnterKeyRule == DefaultEnterKeyRule && newSnippetsRule == SnippetsRule) { return this; } else { return Create( newDismissIfEmpty, newDismissIfLastCharacterDeleted, newDefaultCommitCharacters, newDefaultEnterKeyRule, newSnippetsRule); } } /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfEmpty"/> property changed. /// </summary> public CompletionRules WithDismissIfEmpty(bool dismissIfEmpty) => With(dismissIfEmpty: dismissIfEmpty); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfLastCharacterDeleted"/> property changed. /// </summary> public CompletionRules WithDismissIfLastCharacterDeleted(bool dismissIfLastCharacterDeleted) => With(dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultCommitCharacters"/> property changed. /// </summary> public CompletionRules WithDefaultCommitCharacters(ImmutableArray<char> defaultCommitCharacters) => With(defaultCommitCharacters: defaultCommitCharacters); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultEnterKeyRule"/> property changed. /// </summary> public CompletionRules WithDefaultEnterKeyRule(EnterKeyRule defaultEnterKeyRule) => With(defaultEnterKeyRule: defaultEnterKeyRule); /// <summary> /// Creates a copy of the this <see cref="CompletionRules"/> with the <see cref="SnippetsRule"/> property changed. /// </summary> public CompletionRules WithSnippetsRule(SnippetsRule snippetsRule) => With(snippetsRule: snippetsRule); private static readonly ImmutableArray<char> s_defaultCommitKeys = ImmutableArray.Create( ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\'); /// <summary> /// The default <see cref="CompletionRules"/> if none is otherwise specified. /// </summary> public static readonly CompletionRules Default = new( dismissIfEmpty: false, dismissIfLastCharacterDeleted: false, defaultCommitCharacters: s_defaultCommitKeys, defaultEnterKeyRule: EnterKeyRule.Default, snippetsRule: SnippetsRule.Default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// Presentation and behavior rules for completion. /// </summary> public sealed class CompletionRules { /// <summary> /// True if the completion list should be dismissed if the user's typing causes it to filter /// and display no items. /// </summary> public bool DismissIfEmpty { get; } /// <summary> /// True if the list should be dismissed when the user deletes the last character in the span. /// </summary> public bool DismissIfLastCharacterDeleted { get; } /// <summary> /// The default set of typed characters that cause the selected item to be committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public ImmutableArray<char> DefaultCommitCharacters { get; } /// <summary> /// The default rule that determines if the enter key is passed through to the editor after the selected item has been committed. /// Individual <see cref="CompletionItem"/>s can override this. /// </summary> public EnterKeyRule DefaultEnterKeyRule { get; } /// <summary> /// The rule determining how snippets work. /// </summary> public SnippetsRule SnippetsRule { get; } private CompletionRules( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule, SnippetsRule snippetsRule) { DismissIfEmpty = dismissIfEmpty; DismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted; DefaultCommitCharacters = defaultCommitCharacters.NullToEmpty(); DefaultEnterKeyRule = defaultEnterKeyRule; SnippetsRule = snippetsRule; } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> public static CompletionRules Create( bool dismissIfEmpty, bool dismissIfLastCharacterDeleted, ImmutableArray<char> defaultCommitCharacters, EnterKeyRule defaultEnterKeyRule) { return Create(dismissIfEmpty, dismissIfLastCharacterDeleted, defaultCommitCharacters, defaultEnterKeyRule, SnippetsRule.Default); } /// <summary> /// Creates a new <see cref="CompletionRules"/> instance. /// </summary> /// <param name="dismissIfEmpty">True if the completion list should be dismissed if the user's typing causes it to filter and display no items.</param> /// <param name="dismissIfLastCharacterDeleted">True if the list should be dismissed when the user deletes the last character in the span.</param> /// <param name="defaultCommitCharacters">The default set of typed characters that cause the selected item to be committed.</param> /// <param name="defaultEnterKeyRule">The default rule that determines if the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="snippetsRule">The rule that controls snippets behavior.</param> public static CompletionRules Create( bool dismissIfEmpty = false, bool dismissIfLastCharacterDeleted = false, ImmutableArray<char> defaultCommitCharacters = default, EnterKeyRule defaultEnterKeyRule = EnterKeyRule.Default, SnippetsRule snippetsRule = SnippetsRule.Default) { return new CompletionRules( dismissIfEmpty: dismissIfEmpty, dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted, defaultCommitCharacters: defaultCommitCharacters, defaultEnterKeyRule: defaultEnterKeyRule, snippetsRule: snippetsRule); } private CompletionRules With( Optional<bool> dismissIfEmpty = default, Optional<bool> dismissIfLastCharacterDeleted = default, Optional<ImmutableArray<char>> defaultCommitCharacters = default, Optional<EnterKeyRule> defaultEnterKeyRule = default, Optional<SnippetsRule> snippetsRule = default) { var newDismissIfEmpty = dismissIfEmpty.HasValue ? dismissIfEmpty.Value : DismissIfEmpty; var newDismissIfLastCharacterDeleted = dismissIfLastCharacterDeleted.HasValue ? dismissIfLastCharacterDeleted.Value : DismissIfLastCharacterDeleted; var newDefaultCommitCharacters = defaultCommitCharacters.HasValue ? defaultCommitCharacters.Value : DefaultCommitCharacters; var newDefaultEnterKeyRule = defaultEnterKeyRule.HasValue ? defaultEnterKeyRule.Value : DefaultEnterKeyRule; var newSnippetsRule = snippetsRule.HasValue ? snippetsRule.Value : SnippetsRule; if (newDismissIfEmpty == DismissIfEmpty && newDismissIfLastCharacterDeleted == DismissIfLastCharacterDeleted && newDefaultCommitCharacters == DefaultCommitCharacters && newDefaultEnterKeyRule == DefaultEnterKeyRule && newSnippetsRule == SnippetsRule) { return this; } else { return Create( newDismissIfEmpty, newDismissIfLastCharacterDeleted, newDefaultCommitCharacters, newDefaultEnterKeyRule, newSnippetsRule); } } /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfEmpty"/> property changed. /// </summary> public CompletionRules WithDismissIfEmpty(bool dismissIfEmpty) => With(dismissIfEmpty: dismissIfEmpty); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DismissIfLastCharacterDeleted"/> property changed. /// </summary> public CompletionRules WithDismissIfLastCharacterDeleted(bool dismissIfLastCharacterDeleted) => With(dismissIfLastCharacterDeleted: dismissIfLastCharacterDeleted); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultCommitCharacters"/> property changed. /// </summary> public CompletionRules WithDefaultCommitCharacters(ImmutableArray<char> defaultCommitCharacters) => With(defaultCommitCharacters: defaultCommitCharacters); /// <summary> /// Creates a copy of this <see cref="CompletionRules"/> with the <see cref="DefaultEnterKeyRule"/> property changed. /// </summary> public CompletionRules WithDefaultEnterKeyRule(EnterKeyRule defaultEnterKeyRule) => With(defaultEnterKeyRule: defaultEnterKeyRule); /// <summary> /// Creates a copy of the this <see cref="CompletionRules"/> with the <see cref="SnippetsRule"/> property changed. /// </summary> public CompletionRules WithSnippetsRule(SnippetsRule snippetsRule) => With(snippetsRule: snippetsRule); private static readonly ImmutableArray<char> s_defaultCommitKeys = ImmutableArray.Create( ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\'); /// <summary> /// The default <see cref="CompletionRules"/> if none is otherwise specified. /// </summary> public static readonly CompletionRules Default = new( dismissIfEmpty: false, dismissIfLastCharacterDeleted: false, defaultCommitCharacters: s_defaultCommitKeys, defaultEnterKeyRule: EnterKeyRule.Default, snippetsRule: SnippetsRule.Default); } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/IncrementalParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IncrementalParsingTests : TestBase { private CSharpParseOptions GetOptions(string[] defines) { return new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3, preprocessorSymbols: defines); } private SyntaxTree Parse(string text, params string[] defines) { var options = this.GetOptions(defines); var itext = SourceText.From(text); return SyntaxFactory.ParseSyntaxTree(itext, options); } private SyntaxTree Parse6(string text) { var options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6); var itext = SourceText.From(text); return SyntaxFactory.ParseSyntaxTree(itext, options); } [Fact] public void TestChangeClassNameWithNonMatchingMethod() { var text = "class goo { void m() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeClassNameToNotMatchConstructor() { var text = "class goo { goo() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken, SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.VoidKeyword); } private static void TestDiffsInOrder(ImmutableArray<SyntaxNodeOrToken> diffs, params SyntaxKind[] kinds) { Assert.InRange(diffs.Length, 0, kinds.Length); int diffI = 0; foreach (var kind in kinds) { if (diffI < diffs.Length && diffs[diffI].IsKind(kind)) { diffI++; } } // all diffs must be consumed. Assert.Equal(diffI, diffs.Length); } [Fact] public void TestChangeClassNameToMatchConstructor() { var text = "class goo { bar() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken, SyntaxKind.ConstructorDeclaration); } [Fact] public void TestChangeClassNameToNotMatchDestructor() { var text = "class goo { ~goo() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeClassNameToMatchDestructor() { var text = "class goo { ~bar() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeFromClassToInterface() { var interfaceKeyword = SyntaxFactory.ParseToken("interface"); // prime the memoizer var text = "class goo { public void m() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("class", "interface"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.InterfaceDeclaration, SyntaxKind.InterfaceKeyword); } [Fact] public void TestChangeFromClassToStruct() { var interfaceKeyword = SyntaxFactory.ParseToken("struct"); // prime the memoizer var text = "class goo { public void m() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("class", "struct"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.StructDeclaration, SyntaxKind.StructKeyword); } [Fact] public void TestChangeMethodName() { var text = "class c { void goo(a x, b y) { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeIfCondition() { var text = @" #if GOO class goo { void M() { } } #endif "; var oldTree = this.Parse(text, "GOO", "BAR"); var newTree = oldTree.WithReplaceFirst("GOO", "BAR"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword, SyntaxKind.EndOfFileToken); } [Fact] public void TestChangeDefine() { var text = @" #define GOO #if GOO||BAR class goo { void M() { } } #endif "; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("GOO", "BAR"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword, SyntaxKind.EndOfFileToken); } [Fact] public void TestChangeDefineAndIfElse() { var text = @" #define GOO #if GOO class C { void M() { } } #else class C { void N() { } } #endif "; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("GOO", "BAR"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.IdentifierToken, SyntaxKind.ParameterList, SyntaxKind.Block, SyntaxKind.EndOfFileToken); } [Fact] public void TestAddLineDirective() { var text = @" class C { void M() { } } "; var oldTree = this.Parse(text); var newTree = oldTree.WithInsertAt(0, "#line 100\r\n"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword); } [Fact] public void TestRemoveLineDirective() { var text = @" #line 10 class C { void M() { } } "; var oldTree = this.Parse(text); var newTree = oldTree.WithRemoveFirst("#line 10"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword); } [Fact] public void TestRemoveEndRegionDirective() { var text = @" #if true class A { void a() { } } #region class B { void b() { } } #endregion class C { void c() { } } #endif "; var oldTree = this.Parse(text); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(4, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, oldDirectives[2].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[3].Kind()); var newTree = oldTree.WithRemoveFirst("#endregion"); var errors = newTree.GetCompilationUnitRoot().Errors(); Assert.Equal(2, errors.Length); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code); var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(3, newDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind()); Assert.Equal(SyntaxKind.BadDirectiveTrivia, newDirectives[2].Kind()); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, // class declaration on edge before change SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.Block, SyntaxKind.ClassDeclaration, // class declaration on edge after change SyntaxKind.ClassKeyword, // edge of change and directives different SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive) } [Fact] public void TestAddEndRegionDirective() { var text = @" #if true class A { void a() { } } #region class B { void b() { } } class C { void c() { } } #endif "; var oldTree = this.Parse(text); var errors = oldTree.GetCompilationUnitRoot().Errors(); Assert.Equal(2, errors.Length); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code); var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(3, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind()); Assert.Equal(SyntaxKind.BadDirectiveTrivia, oldDirectives[2].Kind()); var newTree = oldTree.WithInsertBefore("class C", "#endregion\r\n"); errors = newTree.GetCompilationUnitRoot().Errors(); Assert.Equal(0, errors.Length); var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(4, newDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, newDirectives[2].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, newDirectives[3].Kind()); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, // class declaration on edge before change SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.Block, SyntaxKind.ClassDeclaration, // class declaration on edge after change SyntaxKind.ClassKeyword, // edge of change and directives different SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive) } [Fact] public void TestGlobalStatementToStatementChange() { var text = @";a * b"; var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script); var newTree = oldTree.WithInsertAt(0, "{ "); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.GlobalStatement, SyntaxKind.Block, SyntaxKind.OpenBraceToken, SyntaxKind.EmptyStatement, SyntaxKind.LocalDeclarationStatement, SyntaxKind.VariableDeclaration, SyntaxKind.PointerType, SyntaxKind.IdentifierName, SyntaxKind.VariableDeclarator, SyntaxKind.SemicolonToken, // missing SyntaxKind.CloseBraceToken); // missing } [Fact] public void TestStatementToGlobalStatementChange() { var text = @"{; a * b; }"; var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script); var newTree = oldTree.WithRemoveAt(0, 1); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.GlobalStatement, SyntaxKind.EmptyStatement, SyntaxKind.GlobalStatement, SyntaxKind.ExpressionStatement, SyntaxKind.MultiplyExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.SemicolonToken); } #region "Regression" #if false [Fact] public void DevDiv3599() { var text = @"class B { #if false #endif } "; var newText = @"class B { private class E { } #if false #endif } "; var oldTree = this.Parse(text); Assert.Equal(text, oldTree.GetCompilationUnitRoot().ToFullString()); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Count); var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(2, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind); var newTree = oldTree.WithChange(SourceText.From(newText), new TextChangeRange(new TextSpan(7, 0), 16), new TextChangeRange(new TextSpan(8, 0), 13), new TextChangeRange(new TextSpan(9, 0), 7)); //this is the tricky one - it occurs before the trailing trivia of the closing brace //this is the line that fails without the fix to DevDiv #3599 - there's extra text because of a blender error Assert.Equal(newText, newTree.GetCompilationUnitRoot().ToFullString()); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Count); var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(2, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); Assert.Equal(8, diffs.Count); Assert.Equal(SyntaxKind.CompilationUnit, // Everything - different because a descendant is different Assert.Equal(SyntaxKind.ClassDeclaration, // class B - different because a descendant is different //class keyword is reused Assert.Equal(SyntaxKind.IdentifierToken, // B - different because there a change immediately afterward //open brace is reused Assert.Equal(SyntaxKind.ClassDeclaration, // class E - different because it's inserted Assert.Equal(SyntaxKind.PrivateKeyword, // private - different because it's inserted Assert.Equal(SyntaxKind.IdentifierToken, // E - different because it's inserted Assert.Equal(SyntaxKind.OpenBraceToken, // { - different because it's inserted Assert.Equal(SyntaxKind.CloseBraceToken, // } - different because it's inserted //close brace is reused //eof is reused } #endif [Fact] public void Bug892212() { // prove that this incremental change can occur without exception! var text = "/"; var startTree = SyntaxFactory.ParseSyntaxTree(text); var newTree = startTree.WithInsertAt(1, "/"); var fullText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal("//", fullText); } #if false [WorkItem(896260, "Personal")] [Fact]//(Skip = "Bug")] public void RemovePartialFromClassWithIncorrectSpan() { var test = @"partial class C{}"; var resultString = "class C{}"; var startTree = SyntaxTree.Parse(test); var finalString = startTree.GetCompilationUnitRoot().ToString(); var incrementalChange = new TextChange(startTree.Text, SourceText.From(resultString), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) }); // NOTE: The string length here is a bit too short for the change var newTree = startTree.WithChange(incrementalChange); var output = newTree.GetCompilationUnitRoot().ToString(); Assert.Equal(output, resultString); } #endif #if false // can no longer specify an incorrect range [Fact] public void Bug896260() { var test = @"partial class C{}"; var startTree = SyntaxTree.ParseText(test); var finalString = startTree.GetCompilationUnitRoot().ToString(); Exception e = null; try { // NOTE: The string length here is a bit too short for the change var newTree = startTree.WithChange(SourceText.From("class C{}"), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) }); } catch (Exception x) { e = x; } Assert.NotNull(e); } #endif [Fact] public void Bug896262() { var text = SourceText.From(@"partial class C{}"); var startTree = SyntaxFactory.ParseSyntaxTree(text); var finalString = startTree.GetCompilationUnitRoot().ToFullString(); var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), "")); var newTree = startTree.WithChangedText(newText); var finalText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(newText.ToString(), finalText); } [WorkItem(536457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536457")] [Fact] public void RemovePartialFromClassWithCorrectSpan() { var text = SourceText.From(@"partial class C{}"); var startTree = SyntaxFactory.ParseSyntaxTree(text); var finalString = startTree.GetCompilationUnitRoot().ToFullString(); var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), "")); var newTree = startTree.WithChangedText(newText); var output = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(newText.ToString(), output); } [WorkItem(536519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536519")] [Fact] public void AddTopLevelMemberErrorDifference() { SourceText oldText = SourceText.From(@" using System; public d"); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, 'e', out incrementalTree, out parsedTree); // The bug is that the errors are currently different CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536520")] [Fact] public void AddIncompleteStatementErrorDifference() { SourceText oldText = SourceText.From(@" public class Test { static int Main() { "); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, 'r', out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536523")] [Fact] public void DifferentNumberOfErrorsForNonCompletedBlock() { SourceText oldText = SourceText.From(@" public class Test { static int Main() { return 1; "); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, '}', out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536649")] [Fact] public void AddingCharacterOnErrorWithExtern() { SourceText oldText = SourceText.From(@" class C { public extern C(); static int Main () "); char newCharacter = '{'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536650")] [Fact] public void ErrorWithExtraModifiers() { SourceText oldText = SourceText.From(@" class MyClass { internal internal const in"); char newCharacter = 't'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536651")] [Fact] public void CommentsCauseDifferentErrorStrings() { SourceText oldText = SourceText.From(@" class A { static public int Main () { double d = new double(1); /"); char newCharacter = '/'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536652")] [Fact] public void ErrorModifierOnClass() { SourceText oldText = SourceText.From(@" protected class My"); char newCharacter = 'C'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536653")] [Fact] public void ErrorPartialClassWithNoBody() { SourceText oldText = SourceText.From(@" public partial clas"); char newCharacter = 's'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536654")] [Fact] public void ErrorConstKeywordInMethodName() { SourceText oldText = SourceText.From(@" class A { protected virtual void Finalize const () { } } class B"); char newCharacter = ' '; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536655")] [Fact] public void ErrorWithOperatorDeclaration() { SourceText oldText = SourceText.From(@"public class TestClass { public static TestClass operator ++"); char newCharacter = '('; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536661")] [Fact] public void ErrorWithNestedTypeInNew() { SourceText oldText = SourceText.From(@"using System; class Test { static public int Main(String[] args) { AbstractBase b = new AbstractBase."); char newCharacter = 'I'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536662")] [Fact] public void ErrorWithInvalidMethodName() { SourceText oldText = SourceText.From(@"public class MyClass { int -goo("); char newCharacter = ')'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536524")] [Fact] public void AddingAFieldInIncompleteClass() { SourceText oldText = SourceText.From(@" public class Test { "); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, 'C', out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(903526, "DevDiv/Personal")] [Fact] public void AddingTryBlockToMethodOneCharAtTime() { SourceText startingText = SourceText.From(@" public class Test { void Goo() {} // Point }"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText); // Insert a try/catch block inside the method, one char at a time foreach (char c in "try{}catch{}") { syntaxTree = syntaxTree.WithInsertBefore("} // Point", c.ToString()); } Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length); } [WorkItem(903526, "DevDiv/Personal")] [Fact] public void AddingIfBlockToMethodOneCharAtTime() { SourceText startingText = SourceText.From(@" public class Test { void Goo() {} // Point }"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText); foreach (char c in "if(true){}else{}") { syntaxTree = syntaxTree.WithInsertBefore("} // Point", c.ToString()); } Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length); } [Fact] public void AddingWhileBlockToMethodOneCharAtTime() { SourceText startingText = SourceText.From(@" public class Test { void Goo() {} // Point }"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText); foreach (char c in "while(true){}") { syntaxTree = syntaxTree.WithInsertBefore("} // Point", c.ToString()); } Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length); } [WorkItem(536563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536563")] [Fact] public void CommentOutClassKeyword() { SourceText oldText = SourceText.From(@"class MyClass { private enum E {zero, one, two, three}; public const E test = E.two; public static int Main() { return 1; } }"); int locationOfChange = 0, widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536565")] [Fact] public void CommentOutOpeningCurlyOnPrivateDeclaration() { SourceText oldText = SourceText.From(@" private class B{ public class MyClass { private enum E {zero, one, two, three}; public const E test = E.two; public static int Main() { return 1; } }}"); int locationOfChange = 42, widthOfChange = 1; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536567")] [Fact] public void CommentOutBracesOnMethodDeclaration() { SourceText oldText = SourceText.From(@" private class B{ private class MyClass { private enum E {zero, one, two, three}; public const E test = E.two; public int Main() { return 1; } }}"); int locationOfChange = 139, widthOfChange = 2; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536568")] [Fact] public void CommentOutEventKeyword() { SourceText oldText = SourceText.From(@"interface IGoo { event EventHandler E { add { } remove { } } } class Test { public static int Main() { return 1; } }"); int locationOfChange = 20, widthOfChange = 6; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536571")] [Fact] public void CommentOutEventAccessor() { SourceText oldText = SourceText.From(@"interface IGoo { event EventHandler E { add { } remove { } } } class Test { public static int Main() { return 1; } }"); int locationOfChange = 43, widthOfChange = 3; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536573")] [Fact] public void CommentOutDotInUsingAlias() { SourceText oldText = SourceText.From(@"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(a)] class A { public int x = 0; static int Main() { return 0; } } "); int locationOfChange = 12, widthOfChange = 1; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536577")] [Fact] public void CommentOutThisInIndexer() { SourceText oldText = SourceText.From(@"class A { int MyInter.this[int i] { get { return intI + 1; } set { intI = value + 1; } } } "); int locationOfChange = 26, widthOfChange = 4; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536578")] [Fact] public void CommentOutReturnStatementInProperty() { SourceText oldText = SourceText.From(@"public class MyClass { int this[] { get { return intI; } set { intI = value; } } } "); int locationOfChange = 51, widthOfChange = 7; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(905311, "DevDiv/Personal")] [Fact] public void AddSemicolonInForLoop() { SourceText oldText = SourceText.From(@"public class MyClass { void goo() { for (int i = 0 } } "); int locationOfInsert = oldText.ToString().IndexOf('0') + 1; SyntaxTree oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // The bug was that this would simply assert SyntaxTree newTree = oldTree.WithInsertAt(locationOfInsert, ";"); } [WorkItem(536635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536635")] [Fact] public void AddSemicolonAfterStartOfVerbatimString() { var oldText = @"class A { string s = @ } "; var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newTree = oldTree.WithInsertAt(oldText.IndexOf('@'), ";"); } [WorkItem(536717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536717")] [Fact] public void AddReturnWithTriviaAtStart() { string oldText = @"0; } }"; string diffText = "return "; // Get the Original parse tree SyntaxTree origTree = SyntaxFactory.ParseSyntaxTree(oldText); // Get the tree after incremental parse after applying the change SyntaxTree incrTree = origTree.WithInsertAt(0, diffText); string newText = diffText + oldText; // Get the full parse tree with the applied change SyntaxTree fullTree = SyntaxFactory.ParseSyntaxTree(newText); CompareIncToFullParseErrors(incrTree, fullTree); } [WorkItem(536728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536728")] [Fact] public void CommentClassWithGTandGTEOperator() { // the token in question is now converted to skipped text so this check is no longer applicable #if false SourceText oldText = SourceText.From(@"class Test { static bool Test() { if (b21 >>= b22) { } } } "); int locationOfChange = 0, widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "class" to "/*class*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify if the >>= operator in the incremental parse tree is actually 2 separate tokens (> and >=) Assert.Equal(SyntaxKind.GreaterThanToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind); Assert.Equal(SyntaxKind.GreaterThanEqualsToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind); // The full parse tree should also have the above tree structure for the >>= operator Assert.Equal(SyntaxKind.GreaterThanToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind); Assert.Equal(SyntaxKind.GreaterThanEqualsToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind); // Serialize the parse trees and compare the incremental parse tree against the full parse tree // Assert.Equal( parsedTree.GetCompilationUnitRoot().ToXml().ToString(), incrementalTree.GetCompilationUnitRoot().ToXml().ToString()); Assert.True(parsedTree.GetCompilationUnitRoot().IsEquivalentTo(incrementalTree.GetCompilationUnitRoot())); #endif } [WorkItem(536730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536730")] [Fact] public void CodeWithDollarSign() { SourceText oldText = SourceText.From(@"class filesystem{ po$i$; }"); int locationOfChange = 0, widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "class" to "/*class*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify when you roundtrip the text from the full parse with change should match the text from the incremental parse with change // The bug is that the "$" sign was being swallowed on the incremental parse Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString()); } [WorkItem(536731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536731")] [Fact] public void CommentCodeInGOTOStatement() { SourceText oldText = SourceText.From(@"class CSTR020mod{ public static void CSTR020() { ON ERROR GOTO ErrorTrap; } }"); int locationOfChange = oldText.ToString().IndexOf("ON", StringComparison.Ordinal), widthOfChange = 2; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "ON" to "/*ON*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536734")] [Fact] public void CommentConstInConstDeclError() { SourceText oldText = SourceText.From(@"class A { const byte X4var As Byte = 55; } "); int locationOfChange = oldText.ToString().IndexOf("const", StringComparison.Ordinal), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "const" to "/*const*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738")] [Fact] public void CommentClassWithDelegateDecl() { SourceText oldText = SourceText.From(@"public class DynClassDrived { protected delegate void ProtectedDel(dynamic d); } "); int locationOfChange = oldText.ToString().IndexOf("class", StringComparison.Ordinal), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // This function will update "class" to "/*class*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738")] [Fact] public void CommentCloseBraceInPropertyDecl() { SourceText oldText = SourceText.From(@"public class MemberClass { public MyStruct[] Property_MyStructArr { get; set; } public MyEnum[] Property_MyEnumArr { set; private get; } } "); int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update the first closing brace in property declaration Property_MyStructArr "}" to "/*}*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [Fact] public void CommentCloseBraceInInitOnlyPropertyDecl() { SourceText oldText = SourceText.From(@"public class MemberClass { public MyStruct[] Property_MyStructArr { get; init; } public MyEnum[] Property_MyEnumArr { init; private get; } } "); int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5; // This function will update the first closing brace in property declaration Property_MyStructArr "}" to "/*}*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536739")] [Fact] public void CommentFixedInIllegalArrayDecl() { SourceText oldText = SourceText.From(@"class Test { unsafe struct A { public fixed byte Array[dy[""Test""]]; } }"); int locationOfChange = oldText.ToString().IndexOf("fixed", StringComparison.Ordinal), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "fixed" to "/*fixed*/" in oldText above CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536788")] [Fact] public void CommentGlobalUsedAsAlias() { SourceText oldText = SourceText.From( @"using @global=System.Int32; class Test { } "); int locationOfChange = oldText.ToString().IndexOf("@global", StringComparison.Ordinal), widthOfChange = 7; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "@global" to "/*@global*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify if the fully parsed tree and the incrementally parse tree have the same number of children Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count); // Verify if the children of the trees are of the same kind for (int i = 0; i < parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; i++) { Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind()); } } [WorkItem(536789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536789")] [Fact] public void CommentUsingStmtGlobalUsedAsAlias() { SourceText oldText = SourceText.From( @"using @global=System.Int32; class Test { static int Main() { return (@global) 0; } } "); string txtToCmnt = @"using @global=System.Int32;"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "using @global=System.Int32;" to "/*using @global=System.Int32;*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536790")] [Fact] public void CmntMainInCodeWithGlobalQualifierInUnsafe() { SourceText oldText = SourceText.From( @"class Test { unsafe static int Main() { global::System.Int32* p = stackalloc global::System.Int32[5]; } } "); string txtToCmnt = @"Main"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "Main" to "/*Main*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536842, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536842"), WorkItem(543452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543452")] [Fact] public void DelegateDeclInvalidCastException() { SourceText oldText = SourceText.From( @" public delegate void MyDelegate01(dynamic d, int n); [System.CLSCompliant(false)] "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText // The bug is that when you do the incremental parse with the change an InvalidCastException is thrown at runtime. CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify the incrementalTree text and the fully parsed tree text matches Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536843")] [Fact] public void KeyExistsArgumentException() { SourceText oldText = SourceText.From( @" public abstract class AbstractCompiler : ICompiler { protected virtual IDictionary GetOptions() { foreach (string parameter in parameters.Split(' ')) { if (true) { string[] parts = parameter.Remove(0, 1).Split(':'); string key = parts[0].ToLower(); if (true) { } if (true) { } else if (false) { } } } } protected virtual TargetType GetTargetType(IDictionary options) { } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText // The bug is that when you do the incremental parse with the change an ArgumentException is thrown at runtime. CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify the incrementalTree text and the fully parsed tree text matches Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536849")] [Fact] public void QueryExprWithKeywordsAsVariablesAndIncompleteJoin() { SourceText oldText = SourceText.From( @"class Test { static void Main() { var q = from string @params in ( @foreach/9) join"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536865")] [Fact] public void IncompleteGenericTypeParamVarDecl() { SourceText oldText = SourceText.From( @"public class Test { public static int Main() { C<B, A"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '>' character to the end of oldText CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536866")] [Fact] public void IncompleteArglistMethodInvocation() { SourceText oldText = SourceText.From( @"public class Test { public static void Run() { testvar.Test(__arglist(10l, 1"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '2' character to the end of oldText CharByCharIncrementalParse(oldText, '2', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536867")] [Fact] public void IncompleteErrorExtensionMethodDecl() { SourceText oldText = SourceText.From( @"public static class Extensions { public static this Goo(int i, this string str)"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText // The bug is that the Incremental Parser throws a NullReferenceException CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify the incrementalTree text and the fully parsed tree text matches Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536868")] [Fact] public void IncompleteErrorLambdaExpr() { SourceText oldText = SourceText.From( @"public class Program { public static int Main() { D[] a2 = new [] {(int x)="); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '>' character to the end of oldText CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536871")] [Fact] public void IncompleteCodeFollowingXmlDocStyleComment() { SourceText oldText = SourceText.From( @"class C { /// => "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 's' character to the end of oldText CharByCharIncrementalParse(oldText, 's', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536897")] [Fact] public void IncompleteNamespaceFollowingExternError() { SourceText oldText = SourceText.From( @"using C1 = extern; namespace N"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '1' character to the end of oldText CharByCharIncrementalParse(oldText, '1', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536898")] [Fact] public void IncompleteConditionWithJaggedArrayAccess() { SourceText oldText = SourceText.From( @"class A { public static int Main() { if (arr[2][3l] ="); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '=' character to the end of oldText CharByCharIncrementalParse(oldText, '=', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536899")] [Fact] public void TrailingCommentFollowingAttributesInsideMethod() { SourceText oldText = SourceText.From( @"public class goo { public static int Goo { [method:A][goo:A]/"); SyntaxTree incrementalTree; SyntaxTree parsedTree; var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // This function will add the '/' character to the end of oldText CharByCharIncrementalParse(oldText, '/', out incrementalTree, out parsedTree); // Verify that the first child node of the root is equivalent between incremental tree and full parse tree Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString()); } [WorkItem(536901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536901")] [Fact] public void SpecialAttribNameWithDoubleAtToken() { SourceText oldText = SourceText.From( @"[@@X"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ']' character to the end of oldText CharByCharIncrementalParse(oldText, ']', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536903")] [Fact] public void AssertForAttributeWithGenericType() { SourceText oldText = SourceText.From( @"[Goo<i"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'n' character to the end of oldText // The bug is that an assert is thrown when you perform the incremental parse with the change CharByCharIncrementalParse(oldText, 'n', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(539056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539056")] [Fact] public void AssertOnTypingColonInGenericTypeConstraint() { SourceText oldText = SourceText.From( @"class Meta<T>:imeta<T> where T"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ':' character to the end of oldText // The bug is that an assert is thrown when you perform the incremental parse with the change CharByCharIncrementalParse(oldText, ':', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536904")] [Fact] public void ArithmeticExprWithLongConstant() { SourceText oldText = SourceText.From( @"public class arith0018 { public static void Main() { long l1 = 1l/0"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'l' character to the end of oldText CharByCharIncrementalParse(oldText, 'l', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536913")] [Fact] public void AddClassKeywordWithAnonymousMethodThrowsIndexOutOfRangeException() { SourceText oldText = SourceText.From( @"Production<V, T> { private readonly T epsilon=default(T); public Production(T epsilon, Function<SomeType<object>, object> action, V variable, SomeType<object> someType) { ((VoidDelegate)delegate { someType.Iterate(delegate(object o) { System.Console.WriteLine(((BoolDelegate)delegate { return object.Equals(o, this.epsilon); })()); }); })(); } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "class " text to the start of oldText // The bug is that the incremental parser was throwing an IndexOutofRangeException TokenByTokenBottomUp(oldText, "class ", out incrementalTree, out parsedTree); // Verify the incrementalTree roundtrip text is the same as parsedTree roundtrip text Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536914")] [Fact] public void AddClassKeywordWithParamsModifierInAnonymousMethod() { SourceText oldText = SourceText.From( @"Test { static int Goo() { Dele f = delegate(params int[] a) { return 1;}; } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "class " text to the start of oldText TokenByTokenBottomUp(oldText, "class ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536916")] [Fact] public void AddEqualTokenBeforeLongConst() { SourceText oldText = SourceText.From( @"3l; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "=" text to the start of oldText TokenByTokenBottomUp(oldText, "= ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536917")] [Fact] public void AddEqualTokenBeforeHugeConst() { SourceText oldText = SourceText.From( @"18446744073709551616; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "=" text to the start of oldText TokenByTokenBottomUp(oldText, "=", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536616")] [Fact] public void AddEndTagToXmlDocComment() { SourceText oldText = SourceText.From( @"class c1 { /// <Summary> /// < "); SyntaxTree incrementalTree; SyntaxTree parsedTree; TokenByTokenBottomUp(oldText, "/", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537888")] [Fact] public void AddClassKeywordToCodeWithConstructorAndProperty() { SourceText oldText = SourceText.From( @"IntVector { public IntVector(int length) { } public int Length { get { return 1; } } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "class " text to the start of oldText TokenByTokenBottomUp(oldText, "class ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537890")] [Fact] public void AddCurlyBracesToIncompleteCode() { SourceText oldText = SourceText.From( @" int[][] arr; if (arr[1][1] == 0) return 0; else return 1; } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "{ " text to the start of oldText TokenByTokenBottomUp(oldText, "{ ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537891")] [Fact] public void AddOpenParenToIncompleteMethodDeclBeforeDestructor() { SourceText oldText = SourceText.From( @"string s) {} ~Widget() {} "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "(" text to the start of oldText TokenByTokenBottomUp(oldText, "(", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(538977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538977")] [Fact] public void AddTokenToIncompleteQueryExpr() { SourceText oldText = SourceText.From( @"equals abstract select new { }; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "i " text to the start of oldText TokenByTokenBottomUp(oldText, "i ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536986")] [Fact] public void IncompleteGenericInterfaceImplementation() { SourceText oldText = SourceText.From( @"class GenInt : IGenX<int[]>, IGenY<int> { string IGenX<int[]>.m"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '(' character to the end of oldText CharByCharIncrementalParse(oldText, '(', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536988")] [Fact] public void IncompleteIndexerDecl() { SourceText oldText = SourceText.From( @"public class Test { int this[ params int [] args, i"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'n' character to the end of oldText CharByCharIncrementalParse(oldText, 'n', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536990")] [Fact] public void IncompleteGenericVarDeclWithUnderscore() { SourceText oldText = SourceText.From( @"public class Test { public static int Main() { cT ct = _class.TestT<cT, cU"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '>' character to the end of oldText CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536991")] [Fact] public void IncompleteUnsafeArrayInit() { SourceText oldText = SourceText.From( @"unsafe class Test { unsafe void*[] A = {(void*"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ')' character to the end of oldText CharByCharIncrementalParse(oldText, ')', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537012")] [Fact] public void RemoveClassIdentifierTokenWithDelegDecl() { SourceText oldText = SourceText.From( @"class Test { static int Goo() { Dele f = delegate(params int[] a) { return 1;}; } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "Test"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "Test" token from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537889")] [Fact] public void RemoveBracesInExtensionIndexer() { SourceText oldText = SourceText.From( @"public static class Extensions { public static int this(this int x)[int index1] { get { return 9; } } public static int Main() { return 0; } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = ")["; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the ")[" token from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537892, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537892")] [Fact] public void RemoveParensInMethodDeclContainingPartialKeyword() { SourceText oldText = SourceText.From( @"static int Main() { partial"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "()"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "()" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537020")] [Fact] public void IncompleteGlobalQualifierExplInterfaceImpl() { SourceText oldText = SourceText.From( @"class Test : N1.I1 { int global::N1."); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'I' character to the end of oldText CharByCharIncrementalParse(oldText, 'I', out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537033")] [Fact] public void RemoveParensInGetEnumeratorWithPropertyAccess() { SourceText oldText = SourceText.From( @"public class QueueProducerConsumer { public IEnumerator<T> GetEnumerator() { while (true) { if (!value.HasValue) { } } } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "()"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "()" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537053")] [Fact] public void RemoveReturnTypeOnProperty() { SourceText oldText = SourceText.From( @"public class Test { public int Prop { set { D d = delegate { Validator(value); }; } } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "int"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "int" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(538975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538975")] [Fact] public void RemoveTypeOnArrayInParameterWithMethodDeclError() { SourceText oldText = SourceText.From( @"public class A { public void static Main(string[] args) { } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "string"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "string" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537054")] [Fact] public void RemoveReturnTypeOnGenericMethodWithTypeParamConstraint() { SourceText oldText = SourceText.From( @"class Test { public static int M<U>() where U : IDisposable, new() { } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "int"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "int" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537084")] [Fact] public void RemoveNamespaceQualifierFromTypeInIfCondition() { SourceText oldText = SourceText.From( @"public class Driver { public void AddValidations() { if (typeof(K) is System.ValueType) { } } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "System"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "System" text from oldText // The bug is that "Debug.Assert" was thrown by the Incremental Parser with this change RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537092")] [Fact] public void RemoveMethodNameWithLambdaExprInMethodBody() { SourceText oldText = SourceText.From( @"class C { static int Main() { M((x, y) => new Pair<int,double>()); } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "Main"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "Main" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(538978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538978")] [Fact] public void RemoveInitializerOnDeclStatementWithErrors() { SourceText oldText = SourceText.From( @"x public static string S = null; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "null"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "null" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537116")] [Fact] public void CmntEndIfInMethodDecl() { SourceText oldText = SourceText.From( @"class Referenced { #if PUBLIC public #else internal #endif static RecordNotFound Method(){} } //<Code>"); string txtToCmnt = @"internal #endif static RecordNotFound Method(){}"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will comment out the txtToCmnt in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537125")] [Fact] public void CmntAnonTypeInQueryExpr() { SourceText oldText = SourceText.From( @"public class QueryExpressionTest { public static int Main() { var query7 = from a in b join delegate in c on d equals delegate select new { e, delegate }; var query13 = from delegate in f join g in h on delegate equals i select delegate; } }"); string txtToCmnt = @"select new { e, delegate }"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will comment out the txtToCmnt in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537180")] [Fact] public void CmntParamsInExtProperty() { SourceText oldText = SourceText.From( @"public static class Extensions { public static int Goo2(this int x ) { set { var1 = value; } } }"); string txtToCmnt = @"(this int x )"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will comment out the txtToCmnt in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537533")] [Fact] public void MultiCommentInserts() { var str = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // abc // 123 // def if (true) { } else { } } }"; var text = SourceText.From(str); var tree = SyntaxFactory.ParseSyntaxTree(text); var text2 = text.WithChanges( new TextChange(new TextSpan(str.IndexOf(" abc", StringComparison.Ordinal), 0), "//"), new TextChange(new TextSpan(str.IndexOf(" 123", StringComparison.Ordinal), 0), "//"), new TextChange(new TextSpan(str.IndexOf(" def", StringComparison.Ordinal), 0), "//")); var parsedTree = SyntaxFactory.ParseSyntaxTree(text2); var reparsedTree = tree.WithChangedText(text2); CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), reparsedTree.GetCompilationUnitRoot()); } [WorkItem(542236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542236")] [Fact] public void InsertOpenBraceBeforeCodes() { SourceText oldText = SourceText.From(@" this.I = i; }; }"); var startTree = SyntaxFactory.ParseSyntaxTree(oldText); // first make certain this text round trips Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString()); var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), "{")); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void InsertExpressionStatementWithoutSemicolonBefore() { SourceText oldText = SourceText.From(@"System.Console.WriteLine(true) "); var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script); startTree.GetDiagnostics().Verify(); var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @"System.Console.WriteLine(false) ")); AssertEx.AreEqual(@"System.Console.WriteLine(false) System.Console.WriteLine(true) ", newText.ToString()); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script); parsedTree.GetDiagnostics().Verify( // (1,32): error CS1002: ; expected // System.Console.WriteLine(false) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 32)); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void InsertExpressionStatementWithoutSemicolonAfter() { SourceText oldText = SourceText.From(@"System.Console.WriteLine(true) "); var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script); startTree.GetDiagnostics().Verify(); var newText = oldText.WithInsertAt( oldText.Length, @"System.Console.WriteLine(false) "); AssertEx.Equal(@"System.Console.WriteLine(true) System.Console.WriteLine(false) ", newText.ToString()); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script); parsedTree.GetDiagnostics().Verify( // (1,31): error CS1002: ; expected // System.Console.WriteLine(true) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 31)); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void MakeEmbeddedExpressionStatementWithoutSemicolon() { SourceText oldText = SourceText.From(@"System.Console.WriteLine(true) "); var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script); startTree.GetDiagnostics().Verify(); var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @"if (false) ")); AssertEx.Equal(@"if (false) System.Console.WriteLine(true) ", newText.ToString()); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script); parsedTree.GetDiagnostics().Verify( // (2,31): error CS1002: ; expected // System.Console.WriteLine(true) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 31)); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(531404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531404")] [Fact] public void AppendDisabledText() { var text = @"class SmallDictionary { public void Add(int key, int value) { int hash = key + value; #if DEBUG"; var originalTree = this.Parse(text); var changedTree = originalTree.WithInsertAt(text.Length, "\r\n hash++;"); var parsedTree = this.Parse(changedTree.GetCompilationUnitRoot().ToFullString()); Assert.Equal( parsedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan, changedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan); } [Fact, WorkItem(531614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531614")] public void IncrementalParseStopAtEscapeBackSlash() { var text1 = @"using System; class Program { static void Main() { "; var text2 = @" Console.WriteLine(""\'\0\a\b\"; var comp = CSharpTestBase.CreateCompilation(SyntaxFactory.ParseSyntaxTree(String.Empty)); var oldTree = comp.SyntaxTrees.First(); var oldIText = oldTree.GetText(); var span = new TextSpan(oldIText.Length, 0); var change = new TextChange(span, text1); var newIText = oldIText.WithChanges(change); var newTree = oldTree.WithChangedText(newIText); var fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options); var fullText = fullTree.GetCompilationUnitRoot().ToFullString(); var incText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(fullText.Length, incText.Length); Assert.Equal(fullText, incText); // oldTree = newTree; oldIText = oldTree.GetText(); span = new TextSpan(oldIText.Length, 0); change = new TextChange(span, text2); newIText = oldIText.WithChanges(change); newTree = oldTree.WithChangedText(newIText); fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options); fullText = fullTree.GetCompilationUnitRoot().ToFullString(); incText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(fullText.Length, incText.Length); Assert.Equal(fullText, incText); } [Fact, WorkItem(552741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741")] public void IncrementalParseTopDownCommentOutLines() { var text = @"// <Title> Query Expression syntax </Title> // <Description> // from, join, on, equals, into, let, orderby, ascending, descending, group, by // @-with contextual keywords parseable as a type or identifier in a query expression // Various combinations // </Description> // <RelatedBugs></RelatedBugs> //<Expects status=success></Expects> // <Code> using System; using System.Linq; public class from { } public class join { } public class on { } public class equals { } public class into { } public class let { } public class orderby : let { } public class ascending : orderby, descending { } public interface descending { } public class group { } public class by { } public class QueryExpressionTest { public static int Main() { var array02a = new[] { new join(), new join(), new join() } as object[]; var array02b = new[] { new join(), new join(), new join() } as object[]; var query02 = from i in array02a join j in array02b on (@from)i equals (@from)j select new { i, j }; var array03a = new[] { new on(), new on(), new on() } as object[]; var array03b = new[] { new on(), new on(), new on() } as object[]; var query03 = from @on i in array03a join j in array03b on i equals (@on)j select new { i, j }; var array04a = new[] { new equals(), new equals(), new equals() } as object[]; return 0; } } "; var currTree = SyntaxFactory.ParseSyntaxTree(text); var currIText = currTree.GetText(); var items = text.Split('\n'); int currLen = 0; foreach (var item in items) { var span = new TextSpan(currLen, 0); var change = new TextChange(span, "// "); currLen += item.Length + 3; currIText = currIText.WithChanges(change); currTree = currTree.WithChangedText(currIText); var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString()); int incCount = currTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; int fullCount = fullTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } } [Fact, WorkItem(552741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741")] public void IncrementalParseStatementAfterQuery() { var text = @" using System.Linq; class equals { static void Main(string[] args) { equals[] a; var q = from x in args select x; a = new[] { new equals() }; } } "; var currTree = SyntaxFactory.ParseSyntaxTree(text); var currIText = currTree.GetText(); // Insert "// " before the "x" in "select x"; the next statement becomes part of the query. var span = new TextSpan(text.LastIndexOf('x'), 0); var change = new TextChange(span, "// "); currIText = currIText.WithChanges(change); currTree = currTree.WithChangedText(currIText); var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString()); WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact, WorkItem(529260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260")] public void DoNotReuseAnnotatedNodes() { var text = @" class C { } class D { } "; Func<SyntaxTree, GreenNode> extractGreenClassC = tree => tree.GetCompilationUnitRoot().Members.First().Green; // Check reuse after a trivial change in an unannotated tree. { var oldTree = SyntaxFactory.ParseSyntaxTree(text); var newTree = oldTree.WithInsertAt(text.Length, " "); // Class declaration is reused. Assert.Same(extractGreenClassC(oldTree), extractGreenClassC(newTree)); } // Check reuse after a trivial change in an annotated tree. { var tempTree = SyntaxFactory.ParseSyntaxTree(text); var tempRoot = tempTree.GetRoot(); var tempToken = tempRoot.DescendantTokens().First(t => t.Kind() == SyntaxKind.IdentifierToken); var oldRoot = tempRoot.ReplaceToken(tempToken, tempToken.WithAdditionalAnnotations(new SyntaxAnnotation())); Assert.True(oldRoot.ContainsAnnotations, "Should contain annotations."); Assert.Equal(text, oldRoot.ToFullString()); var oldTree = SyntaxFactory.SyntaxTree(oldRoot, options: tempTree.Options, path: tempTree.FilePath); var newTree = oldTree.WithInsertAt(text.Length, " "); var oldClassC = extractGreenClassC(oldTree); var newClassC = extractGreenClassC(newTree); Assert.True(oldClassC.ContainsAnnotations, "Should contain annotations"); Assert.False(newClassC.ContainsAnnotations, "Annotations should have been removed."); // Class declaration is not reused... Assert.NotSame(oldClassC, newClassC); // ...even though the text is the same. Assert.Equal(oldClassC.ToFullString(), newClassC.ToFullString()); var oldToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)oldClassC).Identifier; var newToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)newClassC).Identifier; Assert.True(oldToken.ContainsAnnotations, "Should contain annotations"); Assert.False(newToken.ContainsAnnotations, "Annotations should have been removed."); // Token is not reused... Assert.NotSame(oldToken, newToken); // ...even though the text is the same. Assert.Equal(oldToken.ToFullString(), newToken.ToFullString()); } } [Fact] [WorkItem(658496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658496")] public void DontReuseLambdaParameterAsMethodParameter() { var items = new string[] { "a b.c*/ d => {e(f =>", "/*", }; var oldText = SourceText.From(items[0]); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // f is a simple lambda parameter var change = new TextChange(new TextSpan(0, 0), items[1]); // Prepend var newText = oldText.WithChanges(change); // f is a method decl parameter var incrTree = oldTree.WithChangedText(newText); var fullTree = SyntaxFactory.ParseSyntaxTree(newText); Assert.Equal( fullTree.GetDiagnostics().Select(d => d.ToString()), incrTree.GetDiagnostics().Select(d => d.ToString())); WalkTreeAndVerify(incrTree.GetRoot(), fullTree.GetRoot()); } [Fact] public void TestRescanInterpolatedString() { var interfaceKeyword = SyntaxFactory.ParseToken("interface"); // prime the memoizer var text = @"class goo { public void m() { string s = $""{1} world"" ; } }"; var oldTree = this.Parse6(text); var newTree = oldTree.WithReplaceFirst(@"world"" ", @"world"" "); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); } [Fact] public void Goo() { var oldText = SourceText.From(@" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { } protected abstract int Stuff { get; } } class G: Program { protected override int Stuff { get { throw new NotImplementedException(); } } }"); var newText = SourceText.From(@" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { } protected abstract int Stuff { get; } } class G: Program { protected override int Stuff => { get { throw new NotImplementedException(); } } } "); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newTree = oldTree.WithChangedText(newText); WalkTreeAndVerify(newTree.GetCompilationUnitRoot(), SyntaxFactory.ParseSyntaxTree(newText).GetCompilationUnitRoot()); } [WorkItem(23272, "https://github.com/dotnet/roslyn/issues/23272")] [Fact] public void AddAccessibilityToNullableArray() { var source = @"class A { } class B { A[]? F; }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(" A[]?"), 0); var change = new TextChange(span, "p"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] [WorkItem(37663, "https://github.com/dotnet/roslyn/issues/37663")] public void AssemblyAttributeBeforeNamespace() { var src = @" using System; using System.Linq; [assembly:] namespace N { }"; var tree = SyntaxFactory.ParseSyntaxTree(src); var text = tree.GetText(); var span = new TextSpan(src.IndexOf(":"), 1); var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddBracketInUsingDirective() { var source = @"using System; namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(";"), 0); var change = new TextChange(span, "["); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddAttributeAfterUsingDirective() { var source = @"using System; namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(";") + 1, 0); var change = new TextChange(span, "[Obsolete]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddTrailingModifierInUsingDirective() { var source = @"using System; namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(";") + 1, 0); var change = new TextChange(span, "public"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddTrailingModifierInUsingDirective_2() { var source = @"using System;publi namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "publi"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "c"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void Statement_EditAttributeList_01() { var source = @" class C { void M() { [Attr] void local1() { }; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "Attr"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "1, Attr2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void Statement_EditAttributeList_02() { var source = @" class C { void M() { [Attr1] Method1(); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"Attr1"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, ", Attr2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void Statement_AddAttributeList() { var source = @" class C { void M() { [Attr1] void local1() { }; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"[Attr1]"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " [Attr2]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditStatementWithAttributes_01() { var source = @" class C { void M() { [Attr1] void local1() { Method(); }; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"Method("; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "Arg"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditStatementWithAttributes_02() { var source = @" class C { void M() { [Attr1] Method1(); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"Method"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 1); var change = new TextChange(span, "2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("[Attr] () => { }")] [InlineData("[Attr] x => x")] [InlineData("([Attr] x) => x")] [InlineData("([Attr] int x) => x")] public void Lambda_EditAttributeList(string lambdaExpression) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "Attr"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "1, Attr2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("() => { }", "() => { }")] [InlineData("x => x", "x => x")] [InlineData("(x) => x", "x) => x")] [InlineData("(int x) => x", "int x) => x")] public void Lambda_AddFirstAttributeList(string lambdaExpression, string substring) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(substring), 0); var change = new TextChange(span, "[Attr]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("[Attr1] () => { }")] [InlineData("[Attr1] x => x")] [InlineData("([Attr1] x) => x")] [InlineData("([Attr1] int x) => x")] public void Lambda_AddSecondAttributeList(string lambdaExpression) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"[Attr1]"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " [Attr2]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("[Attr] () => { }")] [InlineData("[Attr] x => x")] [InlineData("([Attr] x) => x")] [InlineData("([Attr] int x) => x")] public void Lambda_RemoveAttributeList(string lambdaExpression) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "[Attr] "; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditGlobalStatementWithAttributes_01() { var source = @" [Attr] x.y(); "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"x.y"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, ".z"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditGlobalStatementWithAttributes_02() { var source = @" [Attr] if (b) { } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"if (b) { }"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " if (c) { }"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditGlobalStatementWithAttributes_03() { var source = @" [Attr] if (b) { } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"if (b) { }"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " else (c) { }"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditNestedStatementWithAttributes_01() { var source = "{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(start: 0, length: 1); // delete first character var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditNestedStatementWithAttributes_02() { var source = "{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(start: 0, length: 0); var change = new TextChange(span, "{ "); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditNestedStatementWithAttributes_03() { var source = "class C { void M() { Goo[Goo] [Goo]if(Goo) { } } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "Goo[Goo]"; var span = new TextSpan(start: source.IndexOf(substring), length: 3); // Goo[Goo] -> [Goo] var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } #endregion #region Helper functions private void WalkTreeAndVerify(SyntaxNodeOrToken incNode, SyntaxNodeOrToken fullNode) { var incChildren = incNode.ChildNodesAndTokens(); var fullChildren = fullNode.ChildNodesAndTokens(); Assert.Equal(incChildren.Count, fullChildren.Count); for (int i = 0; i < incChildren.Count; i++) { var incChild = incChildren[i]; var fullChild = fullChildren[i]; WalkTreeAndVerify(incChild, fullChild); } } private static void CommentOutText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var newText = oldText.WithChanges( new TextChange[] { new TextChange(new TextSpan(locationOfChange, 0), "/*"), new TextChange(new TextSpan(locationOfChange + widthOfChange, 0), "*/") }); var tree = SyntaxFactory.ParseSyntaxTree(oldText); incrementalTree = tree.WithChangedText(newText); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private static void RemoveText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var newText = oldText.WithChanges(new TextChange(new TextSpan(locationOfChange, widthOfChange), "")); var tree = SyntaxFactory.ParseSyntaxTree(oldText); incrementalTree = tree.WithChangedText(newText); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private void CompareIncToFullParseErrors(SyntaxTree incrementalTree, SyntaxTree parsedTree) { var pd = parsedTree.GetDiagnostics(); var id = incrementalTree.GetDiagnostics(); Assert.Equal(pd.Count(), id.Count()); for (int i = 0; i < id.Count(); i++) { Assert.Equal(pd.ElementAt(i).Inspect(), id.ElementAt(i).Inspect()); } ParentChecker.CheckParents(parsedTree.GetCompilationUnitRoot(), parsedTree); ParentChecker.CheckParents(incrementalTree.GetCompilationUnitRoot(), incrementalTree); } private static void CharByCharIncrementalParse(SourceText oldText, char newChar, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var startTree = SyntaxFactory.ParseSyntaxTree(oldText); // first make certain this text round trips Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString()); var newText = oldText.WithChanges(new TextChange(new TextSpan(oldText.Length, 0), newChar.ToString())); incrementalTree = startTree.WithChangedText(newText); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private static void TokenByTokenBottomUp(SourceText oldText, string token, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var startTree = SyntaxFactory.ParseSyntaxTree(oldText); SourceText newText = SourceText.From(token + oldText.ToString()); incrementalTree = startTree.WithInsertAt(0, token); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private static void CompareTreeEquivalence(SyntaxNodeOrToken parsedTreeNode, SyntaxNodeOrToken incrementalTreeNode) { Assert.Equal(parsedTreeNode.Kind(), incrementalTreeNode.Kind()); Assert.Equal(parsedTreeNode.ChildNodesAndTokens().Count, incrementalTreeNode.ChildNodesAndTokens().Count); for (int i = 0; i < parsedTreeNode.ChildNodesAndTokens().Count; i++) { CompareTreeEquivalence(parsedTreeNode.ChildNodesAndTokens()[i], incrementalTreeNode.ChildNodesAndTokens()[i]); } } #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.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IncrementalParsingTests : TestBase { private CSharpParseOptions GetOptions(string[] defines) { return new CSharpParseOptions(languageVersion: LanguageVersion.CSharp3, preprocessorSymbols: defines); } private SyntaxTree Parse(string text, params string[] defines) { var options = this.GetOptions(defines); var itext = SourceText.From(text); return SyntaxFactory.ParseSyntaxTree(itext, options); } private SyntaxTree Parse6(string text) { var options = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6); var itext = SourceText.From(text); return SyntaxFactory.ParseSyntaxTree(itext, options); } [Fact] public void TestChangeClassNameWithNonMatchingMethod() { var text = "class goo { void m() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeClassNameToNotMatchConstructor() { var text = "class goo { goo() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken, SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.VoidKeyword); } private static void TestDiffsInOrder(ImmutableArray<SyntaxNodeOrToken> diffs, params SyntaxKind[] kinds) { Assert.InRange(diffs.Length, 0, kinds.Length); int diffI = 0; foreach (var kind in kinds) { if (diffI < diffs.Length && diffs[diffI].IsKind(kind)) { diffI++; } } // all diffs must be consumed. Assert.Equal(diffI, diffs.Length); } [Fact] public void TestChangeClassNameToMatchConstructor() { var text = "class goo { bar() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken, SyntaxKind.ConstructorDeclaration); } [Fact] public void TestChangeClassNameToNotMatchDestructor() { var text = "class goo { ~goo() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeClassNameToMatchDestructor() { var text = "class goo { ~bar() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeFromClassToInterface() { var interfaceKeyword = SyntaxFactory.ParseToken("interface"); // prime the memoizer var text = "class goo { public void m() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("class", "interface"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.InterfaceDeclaration, SyntaxKind.InterfaceKeyword); } [Fact] public void TestChangeFromClassToStruct() { var interfaceKeyword = SyntaxFactory.ParseToken("struct"); // prime the memoizer var text = "class goo { public void m() { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("class", "struct"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.StructDeclaration, SyntaxKind.StructKeyword); } [Fact] public void TestChangeMethodName() { var text = "class c { void goo(a x, b y) { } }"; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("goo", "bar"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.IdentifierToken); } [Fact] public void TestChangeIfCondition() { var text = @" #if GOO class goo { void M() { } } #endif "; var oldTree = this.Parse(text, "GOO", "BAR"); var newTree = oldTree.WithReplaceFirst("GOO", "BAR"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword, SyntaxKind.EndOfFileToken); } [Fact] public void TestChangeDefine() { var text = @" #define GOO #if GOO||BAR class goo { void M() { } } #endif "; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("GOO", "BAR"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword, SyntaxKind.EndOfFileToken); } [Fact] public void TestChangeDefineAndIfElse() { var text = @" #define GOO #if GOO class C { void M() { } } #else class C { void N() { } } #endif "; var oldTree = this.Parse(text); var newTree = oldTree.WithReplaceFirst("GOO", "BAR"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword, SyntaxKind.IdentifierToken, SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.IdentifierToken, SyntaxKind.ParameterList, SyntaxKind.Block, SyntaxKind.EndOfFileToken); } [Fact] public void TestAddLineDirective() { var text = @" class C { void M() { } } "; var oldTree = this.Parse(text); var newTree = oldTree.WithInsertAt(0, "#line 100\r\n"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword); } [Fact] public void TestRemoveLineDirective() { var text = @" #line 10 class C { void M() { } } "; var oldTree = this.Parse(text); var newTree = oldTree.WithRemoveFirst("#line 10"); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, SyntaxKind.ClassKeyword); } [Fact] public void TestRemoveEndRegionDirective() { var text = @" #if true class A { void a() { } } #region class B { void b() { } } #endregion class C { void c() { } } #endif "; var oldTree = this.Parse(text); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(4, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, oldDirectives[2].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[3].Kind()); var newTree = oldTree.WithRemoveFirst("#endregion"); var errors = newTree.GetCompilationUnitRoot().Errors(); Assert.Equal(2, errors.Length); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code); var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(3, newDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind()); Assert.Equal(SyntaxKind.BadDirectiveTrivia, newDirectives[2].Kind()); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, // class declaration on edge before change SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.Block, SyntaxKind.ClassDeclaration, // class declaration on edge after change SyntaxKind.ClassKeyword, // edge of change and directives different SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive) } [Fact] public void TestAddEndRegionDirective() { var text = @" #if true class A { void a() { } } #region class B { void b() { } } class C { void c() { } } #endif "; var oldTree = this.Parse(text); var errors = oldTree.GetCompilationUnitRoot().Errors(); Assert.Equal(2, errors.Length); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[0].Code); Assert.Equal((int)ErrorCode.ERR_EndRegionDirectiveExpected, errors[1].Code); var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(3, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, oldDirectives[1].Kind()); Assert.Equal(SyntaxKind.BadDirectiveTrivia, oldDirectives[2].Kind()); var newTree = oldTree.WithInsertBefore("class C", "#endregion\r\n"); errors = newTree.GetCompilationUnitRoot().Errors(); Assert.Equal(0, errors.Length); var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(4, newDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, newDirectives[0].Kind()); Assert.Equal(SyntaxKind.RegionDirectiveTrivia, newDirectives[1].Kind()); Assert.Equal(SyntaxKind.EndRegionDirectiveTrivia, newDirectives[2].Kind()); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, newDirectives[3].Kind()); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.ClassDeclaration, // class declaration on edge before change SyntaxKind.MethodDeclaration, SyntaxKind.PredefinedType, SyntaxKind.Block, SyntaxKind.ClassDeclaration, // class declaration on edge after change SyntaxKind.ClassKeyword, // edge of change and directives different SyntaxKind.EndOfFileToken); // directives different (endif becomes bad-directive) } [Fact] public void TestGlobalStatementToStatementChange() { var text = @";a * b"; var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script); var newTree = oldTree.WithInsertAt(0, "{ "); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.GlobalStatement, SyntaxKind.Block, SyntaxKind.OpenBraceToken, SyntaxKind.EmptyStatement, SyntaxKind.LocalDeclarationStatement, SyntaxKind.VariableDeclaration, SyntaxKind.PointerType, SyntaxKind.IdentifierName, SyntaxKind.VariableDeclarator, SyntaxKind.SemicolonToken, // missing SyntaxKind.CloseBraceToken); // missing } [Fact] public void TestStatementToGlobalStatementChange() { var text = @"{; a * b; }"; var oldTree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Script); var newTree = oldTree.WithRemoveAt(0, 1); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); TestDiffsInOrder(diffs, SyntaxKind.CompilationUnit, SyntaxKind.GlobalStatement, SyntaxKind.EmptyStatement, SyntaxKind.GlobalStatement, SyntaxKind.ExpressionStatement, SyntaxKind.MultiplyExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.SemicolonToken); } #region "Regression" #if false [Fact] public void DevDiv3599() { var text = @"class B { #if false #endif } "; var newText = @"class B { private class E { } #if false #endif } "; var oldTree = this.Parse(text); Assert.Equal(text, oldTree.GetCompilationUnitRoot().ToFullString()); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Count); var oldDirectives = oldTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(2, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind); var newTree = oldTree.WithChange(SourceText.From(newText), new TextChangeRange(new TextSpan(7, 0), 16), new TextChangeRange(new TextSpan(8, 0), 13), new TextChangeRange(new TextSpan(9, 0), 7)); //this is the tricky one - it occurs before the trailing trivia of the closing brace //this is the line that fails without the fix to DevDiv #3599 - there's extra text because of a blender error Assert.Equal(newText, newTree.GetCompilationUnitRoot().ToFullString()); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Count); var newDirectives = newTree.GetCompilationUnitRoot().GetDirectives(); Assert.Equal(2, oldDirectives.Count); Assert.Equal(SyntaxKind.IfDirectiveTrivia, oldDirectives[0].Kind); Assert.Equal(SyntaxKind.EndIfDirectiveTrivia, oldDirectives[1].Kind); var diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree); Assert.Equal(8, diffs.Count); Assert.Equal(SyntaxKind.CompilationUnit, // Everything - different because a descendant is different Assert.Equal(SyntaxKind.ClassDeclaration, // class B - different because a descendant is different //class keyword is reused Assert.Equal(SyntaxKind.IdentifierToken, // B - different because there a change immediately afterward //open brace is reused Assert.Equal(SyntaxKind.ClassDeclaration, // class E - different because it's inserted Assert.Equal(SyntaxKind.PrivateKeyword, // private - different because it's inserted Assert.Equal(SyntaxKind.IdentifierToken, // E - different because it's inserted Assert.Equal(SyntaxKind.OpenBraceToken, // { - different because it's inserted Assert.Equal(SyntaxKind.CloseBraceToken, // } - different because it's inserted //close brace is reused //eof is reused } #endif [Fact] public void Bug892212() { // prove that this incremental change can occur without exception! var text = "/"; var startTree = SyntaxFactory.ParseSyntaxTree(text); var newTree = startTree.WithInsertAt(1, "/"); var fullText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal("//", fullText); } #if false [WorkItem(896260, "Personal")] [Fact]//(Skip = "Bug")] public void RemovePartialFromClassWithIncorrectSpan() { var test = @"partial class C{}"; var resultString = "class C{}"; var startTree = SyntaxTree.Parse(test); var finalString = startTree.GetCompilationUnitRoot().ToString(); var incrementalChange = new TextChange(startTree.Text, SourceText.From(resultString), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) }); // NOTE: The string length here is a bit too short for the change var newTree = startTree.WithChange(incrementalChange); var output = newTree.GetCompilationUnitRoot().ToString(); Assert.Equal(output, resultString); } #endif #if false // can no longer specify an incorrect range [Fact] public void Bug896260() { var test = @"partial class C{}"; var startTree = SyntaxTree.ParseText(test); var finalString = startTree.GetCompilationUnitRoot().ToString(); Exception e = null; try { // NOTE: The string length here is a bit too short for the change var newTree = startTree.WithChange(SourceText.From("class C{}"), new TextChangeRange[] { new TextChangeRange(new TextSpan(0, 7), 0) }); } catch (Exception x) { e = x; } Assert.NotNull(e); } #endif [Fact] public void Bug896262() { var text = SourceText.From(@"partial class C{}"); var startTree = SyntaxFactory.ParseSyntaxTree(text); var finalString = startTree.GetCompilationUnitRoot().ToFullString(); var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), "")); var newTree = startTree.WithChangedText(newText); var finalText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(newText.ToString(), finalText); } [WorkItem(536457, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536457")] [Fact] public void RemovePartialFromClassWithCorrectSpan() { var text = SourceText.From(@"partial class C{}"); var startTree = SyntaxFactory.ParseSyntaxTree(text); var finalString = startTree.GetCompilationUnitRoot().ToFullString(); var newText = text.WithChanges(new TextChange(new TextSpan(0, 8), "")); var newTree = startTree.WithChangedText(newText); var output = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(newText.ToString(), output); } [WorkItem(536519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536519")] [Fact] public void AddTopLevelMemberErrorDifference() { SourceText oldText = SourceText.From(@" using System; public d"); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, 'e', out incrementalTree, out parsedTree); // The bug is that the errors are currently different CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536520")] [Fact] public void AddIncompleteStatementErrorDifference() { SourceText oldText = SourceText.From(@" public class Test { static int Main() { "); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, 'r', out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536523")] [Fact] public void DifferentNumberOfErrorsForNonCompletedBlock() { SourceText oldText = SourceText.From(@" public class Test { static int Main() { return 1; "); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, '}', out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536649")] [Fact] public void AddingCharacterOnErrorWithExtern() { SourceText oldText = SourceText.From(@" class C { public extern C(); static int Main () "); char newCharacter = '{'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536650")] [Fact] public void ErrorWithExtraModifiers() { SourceText oldText = SourceText.From(@" class MyClass { internal internal const in"); char newCharacter = 't'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536651")] [Fact] public void CommentsCauseDifferentErrorStrings() { SourceText oldText = SourceText.From(@" class A { static public int Main () { double d = new double(1); /"); char newCharacter = '/'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536652")] [Fact] public void ErrorModifierOnClass() { SourceText oldText = SourceText.From(@" protected class My"); char newCharacter = 'C'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536653")] [Fact] public void ErrorPartialClassWithNoBody() { SourceText oldText = SourceText.From(@" public partial clas"); char newCharacter = 's'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536654")] [Fact] public void ErrorConstKeywordInMethodName() { SourceText oldText = SourceText.From(@" class A { protected virtual void Finalize const () { } } class B"); char newCharacter = ' '; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536655")] [Fact] public void ErrorWithOperatorDeclaration() { SourceText oldText = SourceText.From(@"public class TestClass { public static TestClass operator ++"); char newCharacter = '('; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536661")] [Fact] public void ErrorWithNestedTypeInNew() { SourceText oldText = SourceText.From(@"using System; class Test { static public int Main(String[] args) { AbstractBase b = new AbstractBase."); char newCharacter = 'I'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536662")] [Fact] public void ErrorWithInvalidMethodName() { SourceText oldText = SourceText.From(@"public class MyClass { int -goo("); char newCharacter = ')'; SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, newCharacter, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536524, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536524")] [Fact] public void AddingAFieldInIncompleteClass() { SourceText oldText = SourceText.From(@" public class Test { "); SyntaxTree incrementalTree, parsedTree; CharByCharIncrementalParse(oldText, 'C', out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(903526, "DevDiv/Personal")] [Fact] public void AddingTryBlockToMethodOneCharAtTime() { SourceText startingText = SourceText.From(@" public class Test { void Goo() {} // Point }"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText); // Insert a try/catch block inside the method, one char at a time foreach (char c in "try{}catch{}") { syntaxTree = syntaxTree.WithInsertBefore("} // Point", c.ToString()); } Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length); } [WorkItem(903526, "DevDiv/Personal")] [Fact] public void AddingIfBlockToMethodOneCharAtTime() { SourceText startingText = SourceText.From(@" public class Test { void Goo() {} // Point }"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText); foreach (char c in "if(true){}else{}") { syntaxTree = syntaxTree.WithInsertBefore("} // Point", c.ToString()); } Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length); } [Fact] public void AddingWhileBlockToMethodOneCharAtTime() { SourceText startingText = SourceText.From(@" public class Test { void Goo() {} // Point }"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(startingText); foreach (char c in "while(true){}") { syntaxTree = syntaxTree.WithInsertBefore("} // Point", c.ToString()); } Assert.Equal(0, syntaxTree.GetCompilationUnitRoot().Errors().Length); } [WorkItem(536563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536563")] [Fact] public void CommentOutClassKeyword() { SourceText oldText = SourceText.From(@"class MyClass { private enum E {zero, one, two, three}; public const E test = E.two; public static int Main() { return 1; } }"); int locationOfChange = 0, widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536565")] [Fact] public void CommentOutOpeningCurlyOnPrivateDeclaration() { SourceText oldText = SourceText.From(@" private class B{ public class MyClass { private enum E {zero, one, two, three}; public const E test = E.two; public static int Main() { return 1; } }}"); int locationOfChange = 42, widthOfChange = 1; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536567")] [Fact] public void CommentOutBracesOnMethodDeclaration() { SourceText oldText = SourceText.From(@" private class B{ private class MyClass { private enum E {zero, one, two, three}; public const E test = E.two; public int Main() { return 1; } }}"); int locationOfChange = 139, widthOfChange = 2; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536568")] [Fact] public void CommentOutEventKeyword() { SourceText oldText = SourceText.From(@"interface IGoo { event EventHandler E { add { } remove { } } } class Test { public static int Main() { return 1; } }"); int locationOfChange = 20, widthOfChange = 6; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536571")] [Fact] public void CommentOutEventAccessor() { SourceText oldText = SourceText.From(@"interface IGoo { event EventHandler E { add { } remove { } } } class Test { public static int Main() { return 1; } }"); int locationOfChange = 43, widthOfChange = 3; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536573")] [Fact] public void CommentOutDotInUsingAlias() { SourceText oldText = SourceText.From(@"using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(a)] class A { public int x = 0; static int Main() { return 0; } } "); int locationOfChange = 12, widthOfChange = 1; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536577")] [Fact] public void CommentOutThisInIndexer() { SourceText oldText = SourceText.From(@"class A { int MyInter.this[int i] { get { return intI + 1; } set { intI = value + 1; } } } "); int locationOfChange = 26, widthOfChange = 4; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536578")] [Fact] public void CommentOutReturnStatementInProperty() { SourceText oldText = SourceText.From(@"public class MyClass { int this[] { get { return intI; } set { intI = value; } } } "); int locationOfChange = 51, widthOfChange = 7; SyntaxTree incrementalTree; SyntaxTree parsedTree; CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(905311, "DevDiv/Personal")] [Fact] public void AddSemicolonInForLoop() { SourceText oldText = SourceText.From(@"public class MyClass { void goo() { for (int i = 0 } } "); int locationOfInsert = oldText.ToString().IndexOf('0') + 1; SyntaxTree oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // The bug was that this would simply assert SyntaxTree newTree = oldTree.WithInsertAt(locationOfInsert, ";"); } [WorkItem(536635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536635")] [Fact] public void AddSemicolonAfterStartOfVerbatimString() { var oldText = @"class A { string s = @ } "; var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newTree = oldTree.WithInsertAt(oldText.IndexOf('@'), ";"); } [WorkItem(536717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536717")] [Fact] public void AddReturnWithTriviaAtStart() { string oldText = @"0; } }"; string diffText = "return "; // Get the Original parse tree SyntaxTree origTree = SyntaxFactory.ParseSyntaxTree(oldText); // Get the tree after incremental parse after applying the change SyntaxTree incrTree = origTree.WithInsertAt(0, diffText); string newText = diffText + oldText; // Get the full parse tree with the applied change SyntaxTree fullTree = SyntaxFactory.ParseSyntaxTree(newText); CompareIncToFullParseErrors(incrTree, fullTree); } [WorkItem(536728, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536728")] [Fact] public void CommentClassWithGTandGTEOperator() { // the token in question is now converted to skipped text so this check is no longer applicable #if false SourceText oldText = SourceText.From(@"class Test { static bool Test() { if (b21 >>= b22) { } } } "); int locationOfChange = 0, widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "class" to "/*class*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify if the >>= operator in the incremental parse tree is actually 2 separate tokens (> and >=) Assert.Equal(SyntaxKind.GreaterThanToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind); Assert.Equal(SyntaxKind.GreaterThanEqualsToken, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind); // The full parse tree should also have the above tree structure for the >>= operator Assert.Equal(SyntaxKind.GreaterThanToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[8].Kind); Assert.Equal(SyntaxKind.GreaterThanEqualsToken, parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[2].ChildNodesAndTokens()[9].Kind); // Serialize the parse trees and compare the incremental parse tree against the full parse tree // Assert.Equal( parsedTree.GetCompilationUnitRoot().ToXml().ToString(), incrementalTree.GetCompilationUnitRoot().ToXml().ToString()); Assert.True(parsedTree.GetCompilationUnitRoot().IsEquivalentTo(incrementalTree.GetCompilationUnitRoot())); #endif } [WorkItem(536730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536730")] [Fact] public void CodeWithDollarSign() { SourceText oldText = SourceText.From(@"class filesystem{ po$i$; }"); int locationOfChange = 0, widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "class" to "/*class*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify when you roundtrip the text from the full parse with change should match the text from the incremental parse with change // The bug is that the "$" sign was being swallowed on the incremental parse Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString()); } [WorkItem(536731, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536731")] [Fact] public void CommentCodeInGOTOStatement() { SourceText oldText = SourceText.From(@"class CSTR020mod{ public static void CSTR020() { ON ERROR GOTO ErrorTrap; } }"); int locationOfChange = oldText.ToString().IndexOf("ON", StringComparison.Ordinal), widthOfChange = 2; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "ON" to "/*ON*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536734")] [Fact] public void CommentConstInConstDeclError() { SourceText oldText = SourceText.From(@"class A { const byte X4var As Byte = 55; } "); int locationOfChange = oldText.ToString().IndexOf("const", StringComparison.Ordinal), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "const" to "/*const*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738")] [Fact] public void CommentClassWithDelegateDecl() { SourceText oldText = SourceText.From(@"public class DynClassDrived { protected delegate void ProtectedDel(dynamic d); } "); int locationOfChange = oldText.ToString().IndexOf("class", StringComparison.Ordinal), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // This function will update "class" to "/*class*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536738")] [Fact] public void CommentCloseBraceInPropertyDecl() { SourceText oldText = SourceText.From(@"public class MemberClass { public MyStruct[] Property_MyStructArr { get; set; } public MyEnum[] Property_MyEnumArr { set; private get; } } "); int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update the first closing brace in property declaration Property_MyStructArr "}" to "/*}*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [Fact] public void CommentCloseBraceInInitOnlyPropertyDecl() { SourceText oldText = SourceText.From(@"public class MemberClass { public MyStruct[] Property_MyStructArr { get; init; } public MyEnum[] Property_MyEnumArr { init; private get; } } "); int locationOfChange = oldText.ToString().IndexOf('}'), widthOfChange = 5; // This function will update the first closing brace in property declaration Property_MyStructArr "}" to "/*}*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536739")] [Fact] public void CommentFixedInIllegalArrayDecl() { SourceText oldText = SourceText.From(@"class Test { unsafe struct A { public fixed byte Array[dy[""Test""]]; } }"); int locationOfChange = oldText.ToString().IndexOf("fixed", StringComparison.Ordinal), widthOfChange = 5; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "fixed" to "/*fixed*/" in oldText above CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536788")] [Fact] public void CommentGlobalUsedAsAlias() { SourceText oldText = SourceText.From( @"using @global=System.Int32; class Test { } "); int locationOfChange = oldText.ToString().IndexOf("@global", StringComparison.Ordinal), widthOfChange = 7; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "@global" to "/*@global*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify if the fully parsed tree and the incrementally parse tree have the same number of children Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count, incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count); // Verify if the children of the trees are of the same kind for (int i = 0; i < parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; i++) { Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[i].Kind()); } } [WorkItem(536789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536789")] [Fact] public void CommentUsingStmtGlobalUsedAsAlias() { SourceText oldText = SourceText.From( @"using @global=System.Int32; class Test { static int Main() { return (@global) 0; } } "); string txtToCmnt = @"using @global=System.Int32;"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "using @global=System.Int32;" to "/*using @global=System.Int32;*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536790")] [Fact] public void CmntMainInCodeWithGlobalQualifierInUnsafe() { SourceText oldText = SourceText.From( @"class Test { unsafe static int Main() { global::System.Int32* p = stackalloc global::System.Int32[5]; } } "); string txtToCmnt = @"Main"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will update "Main" to "/*Main*/" in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536842, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536842"), WorkItem(543452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543452")] [Fact] public void DelegateDeclInvalidCastException() { SourceText oldText = SourceText.From( @" public delegate void MyDelegate01(dynamic d, int n); [System.CLSCompliant(false)] "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText // The bug is that when you do the incremental parse with the change an InvalidCastException is thrown at runtime. CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify the incrementalTree text and the fully parsed tree text matches Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536843")] [Fact] public void KeyExistsArgumentException() { SourceText oldText = SourceText.From( @" public abstract class AbstractCompiler : ICompiler { protected virtual IDictionary GetOptions() { foreach (string parameter in parameters.Split(' ')) { if (true) { string[] parts = parameter.Remove(0, 1).Split(':'); string key = parts[0].ToLower(); if (true) { } if (true) { } else if (false) { } } } } protected virtual TargetType GetTargetType(IDictionary options) { } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText // The bug is that when you do the incremental parse with the change an ArgumentException is thrown at runtime. CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify the incrementalTree text and the fully parsed tree text matches Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536849")] [Fact] public void QueryExprWithKeywordsAsVariablesAndIncompleteJoin() { SourceText oldText = SourceText.From( @"class Test { static void Main() { var q = from string @params in ( @foreach/9) join"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536865")] [Fact] public void IncompleteGenericTypeParamVarDecl() { SourceText oldText = SourceText.From( @"public class Test { public static int Main() { C<B, A"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '>' character to the end of oldText CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536866")] [Fact] public void IncompleteArglistMethodInvocation() { SourceText oldText = SourceText.From( @"public class Test { public static void Run() { testvar.Test(__arglist(10l, 1"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '2' character to the end of oldText CharByCharIncrementalParse(oldText, '2', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536867")] [Fact] public void IncompleteErrorExtensionMethodDecl() { SourceText oldText = SourceText.From( @"public static class Extensions { public static this Goo(int i, this string str)"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ' ' character to the end of oldText // The bug is that the Incremental Parser throws a NullReferenceException CharByCharIncrementalParse(oldText, ' ', out incrementalTree, out parsedTree); // Verify the incrementalTree text and the fully parsed tree text matches Assert.Equal(parsedTree.GetText().ToString(), incrementalTree.GetText().ToString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536868")] [Fact] public void IncompleteErrorLambdaExpr() { SourceText oldText = SourceText.From( @"public class Program { public static int Main() { D[] a2 = new [] {(int x)="); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '>' character to the end of oldText CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536871")] [Fact] public void IncompleteCodeFollowingXmlDocStyleComment() { SourceText oldText = SourceText.From( @"class C { /// => "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 's' character to the end of oldText CharByCharIncrementalParse(oldText, 's', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536897")] [Fact] public void IncompleteNamespaceFollowingExternError() { SourceText oldText = SourceText.From( @"using C1 = extern; namespace N"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '1' character to the end of oldText CharByCharIncrementalParse(oldText, '1', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536898")] [Fact] public void IncompleteConditionWithJaggedArrayAccess() { SourceText oldText = SourceText.From( @"class A { public static int Main() { if (arr[2][3l] ="); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '=' character to the end of oldText CharByCharIncrementalParse(oldText, '=', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536899")] [Fact] public void TrailingCommentFollowingAttributesInsideMethod() { SourceText oldText = SourceText.From( @"public class goo { public static int Goo { [method:A][goo:A]/"); SyntaxTree incrementalTree; SyntaxTree parsedTree; var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // This function will add the '/' character to the end of oldText CharByCharIncrementalParse(oldText, '/', out incrementalTree, out parsedTree); // Verify that the first child node of the root is equivalent between incremental tree and full parse tree Assert.Equal(parsedTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString(), incrementalTree.GetCompilationUnitRoot().ChildNodesAndTokens()[0].AsNode().ToFullString()); } [WorkItem(536901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536901")] [Fact] public void SpecialAttribNameWithDoubleAtToken() { SourceText oldText = SourceText.From( @"[@@X"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ']' character to the end of oldText CharByCharIncrementalParse(oldText, ']', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536903")] [Fact] public void AssertForAttributeWithGenericType() { SourceText oldText = SourceText.From( @"[Goo<i"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'n' character to the end of oldText // The bug is that an assert is thrown when you perform the incremental parse with the change CharByCharIncrementalParse(oldText, 'n', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(539056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539056")] [Fact] public void AssertOnTypingColonInGenericTypeConstraint() { SourceText oldText = SourceText.From( @"class Meta<T>:imeta<T> where T"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ':' character to the end of oldText // The bug is that an assert is thrown when you perform the incremental parse with the change CharByCharIncrementalParse(oldText, ':', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536904, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536904")] [Fact] public void ArithmeticExprWithLongConstant() { SourceText oldText = SourceText.From( @"public class arith0018 { public static void Main() { long l1 = 1l/0"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'l' character to the end of oldText CharByCharIncrementalParse(oldText, 'l', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536913, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536913")] [Fact] public void AddClassKeywordWithAnonymousMethodThrowsIndexOutOfRangeException() { SourceText oldText = SourceText.From( @"Production<V, T> { private readonly T epsilon=default(T); public Production(T epsilon, Function<SomeType<object>, object> action, V variable, SomeType<object> someType) { ((VoidDelegate)delegate { someType.Iterate(delegate(object o) { System.Console.WriteLine(((BoolDelegate)delegate { return object.Equals(o, this.epsilon); })()); }); })(); } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "class " text to the start of oldText // The bug is that the incremental parser was throwing an IndexOutofRangeException TokenByTokenBottomUp(oldText, "class ", out incrementalTree, out parsedTree); // Verify the incrementalTree roundtrip text is the same as parsedTree roundtrip text Assert.Equal(parsedTree.GetCompilationUnitRoot().ToFullString(), incrementalTree.GetCompilationUnitRoot().ToFullString()); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536914")] [Fact] public void AddClassKeywordWithParamsModifierInAnonymousMethod() { SourceText oldText = SourceText.From( @"Test { static int Goo() { Dele f = delegate(params int[] a) { return 1;}; } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "class " text to the start of oldText TokenByTokenBottomUp(oldText, "class ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536916")] [Fact] public void AddEqualTokenBeforeLongConst() { SourceText oldText = SourceText.From( @"3l; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "=" text to the start of oldText TokenByTokenBottomUp(oldText, "= ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536917")] [Fact] public void AddEqualTokenBeforeHugeConst() { SourceText oldText = SourceText.From( @"18446744073709551616; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "=" text to the start of oldText TokenByTokenBottomUp(oldText, "=", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536616")] [Fact] public void AddEndTagToXmlDocComment() { SourceText oldText = SourceText.From( @"class c1 { /// <Summary> /// < "); SyntaxTree incrementalTree; SyntaxTree parsedTree; TokenByTokenBottomUp(oldText, "/", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537888")] [Fact] public void AddClassKeywordToCodeWithConstructorAndProperty() { SourceText oldText = SourceText.From( @"IntVector { public IntVector(int length) { } public int Length { get { return 1; } } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "class " text to the start of oldText TokenByTokenBottomUp(oldText, "class ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537890")] [Fact] public void AddCurlyBracesToIncompleteCode() { SourceText oldText = SourceText.From( @" int[][] arr; if (arr[1][1] == 0) return 0; else return 1; } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "{ " text to the start of oldText TokenByTokenBottomUp(oldText, "{ ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537891")] [Fact] public void AddOpenParenToIncompleteMethodDeclBeforeDestructor() { SourceText oldText = SourceText.From( @"string s) {} ~Widget() {} "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "(" text to the start of oldText TokenByTokenBottomUp(oldText, "(", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(538977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538977")] [Fact] public void AddTokenToIncompleteQueryExpr() { SourceText oldText = SourceText.From( @"equals abstract select new { }; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the "i " text to the start of oldText TokenByTokenBottomUp(oldText, "i ", out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536986")] [Fact] public void IncompleteGenericInterfaceImplementation() { SourceText oldText = SourceText.From( @"class GenInt : IGenX<int[]>, IGenY<int> { string IGenX<int[]>.m"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '(' character to the end of oldText CharByCharIncrementalParse(oldText, '(', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536988")] [Fact] public void IncompleteIndexerDecl() { SourceText oldText = SourceText.From( @"public class Test { int this[ params int [] args, i"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'n' character to the end of oldText CharByCharIncrementalParse(oldText, 'n', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536990")] [Fact] public void IncompleteGenericVarDeclWithUnderscore() { SourceText oldText = SourceText.From( @"public class Test { public static int Main() { cT ct = _class.TestT<cT, cU"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the '>' character to the end of oldText CharByCharIncrementalParse(oldText, '>', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(536991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536991")] [Fact] public void IncompleteUnsafeArrayInit() { SourceText oldText = SourceText.From( @"unsafe class Test { unsafe void*[] A = {(void*"); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the ')' character to the end of oldText CharByCharIncrementalParse(oldText, ')', out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537012")] [Fact] public void RemoveClassIdentifierTokenWithDelegDecl() { SourceText oldText = SourceText.From( @"class Test { static int Goo() { Dele f = delegate(params int[] a) { return 1;}; } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "Test"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "Test" token from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537889")] [Fact] public void RemoveBracesInExtensionIndexer() { SourceText oldText = SourceText.From( @"public static class Extensions { public static int this(this int x)[int index1] { get { return 9; } } public static int Main() { return 0; } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = ")["; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the ")[" token from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537892, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537892")] [Fact] public void RemoveParensInMethodDeclContainingPartialKeyword() { SourceText oldText = SourceText.From( @"static int Main() { partial"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "()"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "()" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537020")] [Fact] public void IncompleteGlobalQualifierExplInterfaceImpl() { SourceText oldText = SourceText.From( @"class Test : N1.I1 { int global::N1."); SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will add the 'I' character to the end of oldText CharByCharIncrementalParse(oldText, 'I', out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537033, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537033")] [Fact] public void RemoveParensInGetEnumeratorWithPropertyAccess() { SourceText oldText = SourceText.From( @"public class QueueProducerConsumer { public IEnumerator<T> GetEnumerator() { while (true) { if (!value.HasValue) { } } } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "()"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "()" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537053")] [Fact] public void RemoveReturnTypeOnProperty() { SourceText oldText = SourceText.From( @"public class Test { public int Prop { set { D d = delegate { Validator(value); }; } } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "int"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "int" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(538975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538975")] [Fact] public void RemoveTypeOnArrayInParameterWithMethodDeclError() { SourceText oldText = SourceText.From( @"public class A { public void static Main(string[] args) { } } "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "string"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "string" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537054")] [Fact] public void RemoveReturnTypeOnGenericMethodWithTypeParamConstraint() { SourceText oldText = SourceText.From( @"class Test { public static int M<U>() where U : IDisposable, new() { } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "int"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "int" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537084")] [Fact] public void RemoveNamespaceQualifierFromTypeInIfCondition() { SourceText oldText = SourceText.From( @"public class Driver { public void AddValidations() { if (typeof(K) is System.ValueType) { } } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "System"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "System" text from oldText // The bug is that "Debug.Assert" was thrown by the Incremental Parser with this change RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537092")] [Fact] public void RemoveMethodNameWithLambdaExprInMethodBody() { SourceText oldText = SourceText.From( @"class C { static int Main() { M((x, y) => new Pair<int,double>()); } }"); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "Main"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "Main" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(538978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538978")] [Fact] public void RemoveInitializerOnDeclStatementWithErrors() { SourceText oldText = SourceText.From( @"x public static string S = null; "); SyntaxTree incrementalTree; SyntaxTree parsedTree; string textToRemove = "null"; int locationOfChange = oldText.ToString().IndexOf(textToRemove, StringComparison.Ordinal); int widthOfChange = textToRemove.Length; // This function will remove the "null" text from oldText RemoveText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537116")] [Fact] public void CmntEndIfInMethodDecl() { SourceText oldText = SourceText.From( @"class Referenced { #if PUBLIC public #else internal #endif static RecordNotFound Method(){} } //<Code>"); string txtToCmnt = @"internal #endif static RecordNotFound Method(){}"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will comment out the txtToCmnt in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537125")] [Fact] public void CmntAnonTypeInQueryExpr() { SourceText oldText = SourceText.From( @"public class QueryExpressionTest { public static int Main() { var query7 = from a in b join delegate in c on d equals delegate select new { e, delegate }; var query13 = from delegate in f join g in h on delegate equals i select delegate; } }"); string txtToCmnt = @"select new { e, delegate }"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will comment out the txtToCmnt in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the errors from the fully parsed tree with the change and the incrementally parsed tree are the same CompareIncToFullParseErrors(incrementalTree, parsedTree); } [WorkItem(537180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537180")] [Fact] public void CmntParamsInExtProperty() { SourceText oldText = SourceText.From( @"public static class Extensions { public static int Goo2(this int x ) { set { var1 = value; } } }"); string txtToCmnt = @"(this int x )"; int locationOfChange = oldText.ToString().IndexOf(txtToCmnt, StringComparison.Ordinal), widthOfChange = txtToCmnt.Length; SyntaxTree incrementalTree; SyntaxTree parsedTree; // This function will comment out the txtToCmnt in oldText CommentOutText(oldText, locationOfChange, widthOfChange, out incrementalTree, out parsedTree); // Verify that the fully parsed tree is structurally equivalent to the incrementally parsed tree CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), incrementalTree.GetCompilationUnitRoot()); } [WorkItem(537533, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537533")] [Fact] public void MultiCommentInserts() { var str = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // abc // 123 // def if (true) { } else { } } }"; var text = SourceText.From(str); var tree = SyntaxFactory.ParseSyntaxTree(text); var text2 = text.WithChanges( new TextChange(new TextSpan(str.IndexOf(" abc", StringComparison.Ordinal), 0), "//"), new TextChange(new TextSpan(str.IndexOf(" 123", StringComparison.Ordinal), 0), "//"), new TextChange(new TextSpan(str.IndexOf(" def", StringComparison.Ordinal), 0), "//")); var parsedTree = SyntaxFactory.ParseSyntaxTree(text2); var reparsedTree = tree.WithChangedText(text2); CompareTreeEquivalence(parsedTree.GetCompilationUnitRoot(), reparsedTree.GetCompilationUnitRoot()); } [WorkItem(542236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542236")] [Fact] public void InsertOpenBraceBeforeCodes() { SourceText oldText = SourceText.From(@" this.I = i; }; }"); var startTree = SyntaxFactory.ParseSyntaxTree(oldText); // first make certain this text round trips Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString()); var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), "{")); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void InsertExpressionStatementWithoutSemicolonBefore() { SourceText oldText = SourceText.From(@"System.Console.WriteLine(true) "); var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script); startTree.GetDiagnostics().Verify(); var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @"System.Console.WriteLine(false) ")); AssertEx.AreEqual(@"System.Console.WriteLine(false) System.Console.WriteLine(true) ", newText.ToString()); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script); parsedTree.GetDiagnostics().Verify( // (1,32): error CS1002: ; expected // System.Console.WriteLine(false) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 32)); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void InsertExpressionStatementWithoutSemicolonAfter() { SourceText oldText = SourceText.From(@"System.Console.WriteLine(true) "); var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script); startTree.GetDiagnostics().Verify(); var newText = oldText.WithInsertAt( oldText.Length, @"System.Console.WriteLine(false) "); AssertEx.Equal(@"System.Console.WriteLine(true) System.Console.WriteLine(false) ", newText.ToString()); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script); parsedTree.GetDiagnostics().Verify( // (1,31): error CS1002: ; expected // System.Console.WriteLine(true) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 31)); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void MakeEmbeddedExpressionStatementWithoutSemicolon() { SourceText oldText = SourceText.From(@"System.Console.WriteLine(true) "); var startTree = SyntaxFactory.ParseSyntaxTree(oldText, options: TestOptions.Script); startTree.GetDiagnostics().Verify(); var newText = oldText.WithChanges(new TextChange(new TextSpan(0, 0), @"if (false) ")); AssertEx.Equal(@"if (false) System.Console.WriteLine(true) ", newText.ToString()); var reparsedTree = startTree.WithChangedText(newText); var parsedTree = SyntaxFactory.ParseSyntaxTree(newText, options: TestOptions.Script); parsedTree.GetDiagnostics().Verify( // (2,31): error CS1002: ; expected // System.Console.WriteLine(true) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(2, 31)); CompareIncToFullParseErrors(reparsedTree, parsedTree); } [WorkItem(531404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531404")] [Fact] public void AppendDisabledText() { var text = @"class SmallDictionary { public void Add(int key, int value) { int hash = key + value; #if DEBUG"; var originalTree = this.Parse(text); var changedTree = originalTree.WithInsertAt(text.Length, "\r\n hash++;"); var parsedTree = this.Parse(changedTree.GetCompilationUnitRoot().ToFullString()); Assert.Equal( parsedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan, changedTree.GetCompilationUnitRoot().EndOfFileToken.FullSpan); } [Fact, WorkItem(531614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531614")] public void IncrementalParseStopAtEscapeBackSlash() { var text1 = @"using System; class Program { static void Main() { "; var text2 = @" Console.WriteLine(""\'\0\a\b\"; var comp = CSharpTestBase.CreateCompilation(SyntaxFactory.ParseSyntaxTree(String.Empty)); var oldTree = comp.SyntaxTrees.First(); var oldIText = oldTree.GetText(); var span = new TextSpan(oldIText.Length, 0); var change = new TextChange(span, text1); var newIText = oldIText.WithChanges(change); var newTree = oldTree.WithChangedText(newIText); var fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options); var fullText = fullTree.GetCompilationUnitRoot().ToFullString(); var incText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(fullText.Length, incText.Length); Assert.Equal(fullText, incText); // oldTree = newTree; oldIText = oldTree.GetText(); span = new TextSpan(oldIText.Length, 0); change = new TextChange(span, text2); newIText = oldIText.WithChanges(change); newTree = oldTree.WithChangedText(newIText); fullTree = SyntaxFactory.ParseSyntaxTree(newIText.ToString(), options: newTree.Options); fullText = fullTree.GetCompilationUnitRoot().ToFullString(); incText = newTree.GetCompilationUnitRoot().ToFullString(); Assert.Equal(fullText.Length, incText.Length); Assert.Equal(fullText, incText); } [Fact, WorkItem(552741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741")] public void IncrementalParseTopDownCommentOutLines() { var text = @"// <Title> Query Expression syntax </Title> // <Description> // from, join, on, equals, into, let, orderby, ascending, descending, group, by // @-with contextual keywords parseable as a type or identifier in a query expression // Various combinations // </Description> // <RelatedBugs></RelatedBugs> //<Expects status=success></Expects> // <Code> using System; using System.Linq; public class from { } public class join { } public class on { } public class equals { } public class into { } public class let { } public class orderby : let { } public class ascending : orderby, descending { } public interface descending { } public class group { } public class by { } public class QueryExpressionTest { public static int Main() { var array02a = new[] { new join(), new join(), new join() } as object[]; var array02b = new[] { new join(), new join(), new join() } as object[]; var query02 = from i in array02a join j in array02b on (@from)i equals (@from)j select new { i, j }; var array03a = new[] { new on(), new on(), new on() } as object[]; var array03b = new[] { new on(), new on(), new on() } as object[]; var query03 = from @on i in array03a join j in array03b on i equals (@on)j select new { i, j }; var array04a = new[] { new equals(), new equals(), new equals() } as object[]; return 0; } } "; var currTree = SyntaxFactory.ParseSyntaxTree(text); var currIText = currTree.GetText(); var items = text.Split('\n'); int currLen = 0; foreach (var item in items) { var span = new TextSpan(currLen, 0); var change = new TextChange(span, "// "); currLen += item.Length + 3; currIText = currIText.WithChanges(change); currTree = currTree.WithChangedText(currIText); var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString()); int incCount = currTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; int fullCount = fullTree.GetCompilationUnitRoot().ChildNodesAndTokens().Count; WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } } [Fact, WorkItem(552741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552741")] public void IncrementalParseStatementAfterQuery() { var text = @" using System.Linq; class equals { static void Main(string[] args) { equals[] a; var q = from x in args select x; a = new[] { new equals() }; } } "; var currTree = SyntaxFactory.ParseSyntaxTree(text); var currIText = currTree.GetText(); // Insert "// " before the "x" in "select x"; the next statement becomes part of the query. var span = new TextSpan(text.LastIndexOf('x'), 0); var change = new TextChange(span, "// "); currIText = currIText.WithChanges(change); currTree = currTree.WithChangedText(currIText); var fullTree = SyntaxFactory.ParseSyntaxTree(currIText.ToString()); WalkTreeAndVerify(currTree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact, WorkItem(529260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260")] public void DoNotReuseAnnotatedNodes() { var text = @" class C { } class D { } "; Func<SyntaxTree, GreenNode> extractGreenClassC = tree => tree.GetCompilationUnitRoot().Members.First().Green; // Check reuse after a trivial change in an unannotated tree. { var oldTree = SyntaxFactory.ParseSyntaxTree(text); var newTree = oldTree.WithInsertAt(text.Length, " "); // Class declaration is reused. Assert.Same(extractGreenClassC(oldTree), extractGreenClassC(newTree)); } // Check reuse after a trivial change in an annotated tree. { var tempTree = SyntaxFactory.ParseSyntaxTree(text); var tempRoot = tempTree.GetRoot(); var tempToken = tempRoot.DescendantTokens().First(t => t.Kind() == SyntaxKind.IdentifierToken); var oldRoot = tempRoot.ReplaceToken(tempToken, tempToken.WithAdditionalAnnotations(new SyntaxAnnotation())); Assert.True(oldRoot.ContainsAnnotations, "Should contain annotations."); Assert.Equal(text, oldRoot.ToFullString()); var oldTree = SyntaxFactory.SyntaxTree(oldRoot, options: tempTree.Options, path: tempTree.FilePath); var newTree = oldTree.WithInsertAt(text.Length, " "); var oldClassC = extractGreenClassC(oldTree); var newClassC = extractGreenClassC(newTree); Assert.True(oldClassC.ContainsAnnotations, "Should contain annotations"); Assert.False(newClassC.ContainsAnnotations, "Annotations should have been removed."); // Class declaration is not reused... Assert.NotSame(oldClassC, newClassC); // ...even though the text is the same. Assert.Equal(oldClassC.ToFullString(), newClassC.ToFullString()); var oldToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)oldClassC).Identifier; var newToken = ((Syntax.InternalSyntax.ClassDeclarationSyntax)newClassC).Identifier; Assert.True(oldToken.ContainsAnnotations, "Should contain annotations"); Assert.False(newToken.ContainsAnnotations, "Annotations should have been removed."); // Token is not reused... Assert.NotSame(oldToken, newToken); // ...even though the text is the same. Assert.Equal(oldToken.ToFullString(), newToken.ToFullString()); } } [Fact] [WorkItem(658496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658496")] public void DontReuseLambdaParameterAsMethodParameter() { var items = new string[] { "a b.c*/ d => {e(f =>", "/*", }; var oldText = SourceText.From(items[0]); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); // f is a simple lambda parameter var change = new TextChange(new TextSpan(0, 0), items[1]); // Prepend var newText = oldText.WithChanges(change); // f is a method decl parameter var incrTree = oldTree.WithChangedText(newText); var fullTree = SyntaxFactory.ParseSyntaxTree(newText); Assert.Equal( fullTree.GetDiagnostics().Select(d => d.ToString()), incrTree.GetDiagnostics().Select(d => d.ToString())); WalkTreeAndVerify(incrTree.GetRoot(), fullTree.GetRoot()); } [Fact] public void TestRescanInterpolatedString() { var interfaceKeyword = SyntaxFactory.ParseToken("interface"); // prime the memoizer var text = @"class goo { public void m() { string s = $""{1} world"" ; } }"; var oldTree = this.Parse6(text); var newTree = oldTree.WithReplaceFirst(@"world"" ", @"world"" "); Assert.Equal(0, oldTree.GetCompilationUnitRoot().Errors().Length); Assert.Equal(0, newTree.GetCompilationUnitRoot().Errors().Length); } [Fact] public void Goo() { var oldText = SourceText.From(@" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { } protected abstract int Stuff { get; } } class G: Program { protected override int Stuff { get { throw new NotImplementedException(); } } }"); var newText = SourceText.From(@" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { } protected abstract int Stuff { get; } } class G: Program { protected override int Stuff => { get { throw new NotImplementedException(); } } } "); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newTree = oldTree.WithChangedText(newText); WalkTreeAndVerify(newTree.GetCompilationUnitRoot(), SyntaxFactory.ParseSyntaxTree(newText).GetCompilationUnitRoot()); } [WorkItem(23272, "https://github.com/dotnet/roslyn/issues/23272")] [Fact] public void AddAccessibilityToNullableArray() { var source = @"class A { } class B { A[]? F; }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(" A[]?"), 0); var change = new TextChange(span, "p"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] [WorkItem(37663, "https://github.com/dotnet/roslyn/issues/37663")] public void AssemblyAttributeBeforeNamespace() { var src = @" using System; using System.Linq; [assembly:] namespace N { }"; var tree = SyntaxFactory.ParseSyntaxTree(src); var text = tree.GetText(); var span = new TextSpan(src.IndexOf(":"), 1); var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddBracketInUsingDirective() { var source = @"using System; namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(";"), 0); var change = new TextChange(span, "["); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddAttributeAfterUsingDirective() { var source = @"using System; namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(";") + 1, 0); var change = new TextChange(span, "[Obsolete]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddTrailingModifierInUsingDirective() { var source = @"using System; namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(";") + 1, 0); var change = new TextChange(span, "public"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [WorkItem(37665, "https://github.com/dotnet/roslyn/issues/37665")] [Fact] public void AddTrailingModifierInUsingDirective_2() { var source = @"using System;publi namespace NS { class A { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "publi"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "c"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void Statement_EditAttributeList_01() { var source = @" class C { void M() { [Attr] void local1() { }; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "Attr"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "1, Attr2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void Statement_EditAttributeList_02() { var source = @" class C { void M() { [Attr1] Method1(); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"Attr1"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, ", Attr2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void Statement_AddAttributeList() { var source = @" class C { void M() { [Attr1] void local1() { }; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"[Attr1]"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " [Attr2]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditStatementWithAttributes_01() { var source = @" class C { void M() { [Attr1] void local1() { Method(); }; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"Method("; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "Arg"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditStatementWithAttributes_02() { var source = @" class C { void M() { [Attr1] Method1(); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"Method"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 1); var change = new TextChange(span, "2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("[Attr] () => { }")] [InlineData("[Attr] x => x")] [InlineData("([Attr] x) => x")] [InlineData("([Attr] int x) => x")] public void Lambda_EditAttributeList(string lambdaExpression) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "Attr"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, "1, Attr2"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("() => { }", "() => { }")] [InlineData("x => x", "x => x")] [InlineData("(x) => x", "x) => x")] [InlineData("(int x) => x", "int x) => x")] public void Lambda_AddFirstAttributeList(string lambdaExpression, string substring) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(source.IndexOf(substring), 0); var change = new TextChange(span, "[Attr]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("[Attr1] () => { }")] [InlineData("[Attr1] x => x")] [InlineData("([Attr1] x) => x")] [InlineData("([Attr1] int x) => x")] public void Lambda_AddSecondAttributeList(string lambdaExpression) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"[Attr1]"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " [Attr2]"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Theory] [InlineData("[Attr] () => { }")] [InlineData("[Attr] x => x")] [InlineData("([Attr] x) => x")] [InlineData("([Attr] int x) => x")] public void Lambda_RemoveAttributeList(string lambdaExpression) { var source = $@"class Program {{ static void Main() {{ F({lambdaExpression}); }} }}"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "[Attr] "; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditGlobalStatementWithAttributes_01() { var source = @" [Attr] x.y(); "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"x.y"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, ".z"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditGlobalStatementWithAttributes_02() { var source = @" [Attr] if (b) { } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"if (b) { }"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " if (c) { }"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditGlobalStatementWithAttributes_03() { var source = @" [Attr] if (b) { } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = @"if (b) { }"; var span = new TextSpan(source.IndexOf(substring) + substring.Length, 0); var change = new TextChange(span, " else (c) { }"); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditNestedStatementWithAttributes_01() { var source = "{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(start: 0, length: 1); // delete first character var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditNestedStatementWithAttributes_02() { var source = "{ [Goo]Goo(); [Goo]Goo(); [Goo]Goo(); }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var span = new TextSpan(start: 0, length: 0); var change = new TextChange(span, "{ "); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } [Fact] public void EditNestedStatementWithAttributes_03() { var source = "class C { void M() { Goo[Goo] [Goo]if(Goo) { } } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var text = tree.GetText(); var substring = "Goo[Goo]"; var span = new TextSpan(start: source.IndexOf(substring), length: 3); // Goo[Goo] -> [Goo] var change = new TextChange(span, ""); text = text.WithChanges(change); tree = tree.WithChangedText(text); var fullTree = SyntaxFactory.ParseSyntaxTree(text.ToString()); WalkTreeAndVerify(tree.GetCompilationUnitRoot(), fullTree.GetCompilationUnitRoot()); } #endregion #region Helper functions private void WalkTreeAndVerify(SyntaxNodeOrToken incNode, SyntaxNodeOrToken fullNode) { var incChildren = incNode.ChildNodesAndTokens(); var fullChildren = fullNode.ChildNodesAndTokens(); Assert.Equal(incChildren.Count, fullChildren.Count); for (int i = 0; i < incChildren.Count; i++) { var incChild = incChildren[i]; var fullChild = fullChildren[i]; WalkTreeAndVerify(incChild, fullChild); } } private static void CommentOutText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var newText = oldText.WithChanges( new TextChange[] { new TextChange(new TextSpan(locationOfChange, 0), "/*"), new TextChange(new TextSpan(locationOfChange + widthOfChange, 0), "*/") }); var tree = SyntaxFactory.ParseSyntaxTree(oldText); incrementalTree = tree.WithChangedText(newText); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private static void RemoveText(SourceText oldText, int locationOfChange, int widthOfChange, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var newText = oldText.WithChanges(new TextChange(new TextSpan(locationOfChange, widthOfChange), "")); var tree = SyntaxFactory.ParseSyntaxTree(oldText); incrementalTree = tree.WithChangedText(newText); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private void CompareIncToFullParseErrors(SyntaxTree incrementalTree, SyntaxTree parsedTree) { var pd = parsedTree.GetDiagnostics(); var id = incrementalTree.GetDiagnostics(); Assert.Equal(pd.Count(), id.Count()); for (int i = 0; i < id.Count(); i++) { Assert.Equal(pd.ElementAt(i).Inspect(), id.ElementAt(i).Inspect()); } ParentChecker.CheckParents(parsedTree.GetCompilationUnitRoot(), parsedTree); ParentChecker.CheckParents(incrementalTree.GetCompilationUnitRoot(), incrementalTree); } private static void CharByCharIncrementalParse(SourceText oldText, char newChar, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var startTree = SyntaxFactory.ParseSyntaxTree(oldText); // first make certain this text round trips Assert.Equal(oldText.ToString(), startTree.GetCompilationUnitRoot().ToFullString()); var newText = oldText.WithChanges(new TextChange(new TextSpan(oldText.Length, 0), newChar.ToString())); incrementalTree = startTree.WithChangedText(newText); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private static void TokenByTokenBottomUp(SourceText oldText, string token, out SyntaxTree incrementalTree, out SyntaxTree parsedTree) { var startTree = SyntaxFactory.ParseSyntaxTree(oldText); SourceText newText = SourceText.From(token + oldText.ToString()); incrementalTree = startTree.WithInsertAt(0, token); parsedTree = SyntaxFactory.ParseSyntaxTree(newText); } private static void CompareTreeEquivalence(SyntaxNodeOrToken parsedTreeNode, SyntaxNodeOrToken incrementalTreeNode) { Assert.Equal(parsedTreeNode.Kind(), incrementalTreeNode.Kind()); Assert.Equal(parsedTreeNode.ChildNodesAndTokens().Count, incrementalTreeNode.ChildNodesAndTokens().Count); for (int i = 0; i < parsedTreeNode.ChildNodesAndTokens().Count; i++) { CompareTreeEquivalence(parsedTreeNode.ChildNodesAndTokens()[i], incrementalTreeNode.ChildNodesAndTokens()[i]); } } #endregion } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Tests/TestWriter.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. '----------------------------------------------------------------------------------------------------------- ' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated ' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data ' structures like the kinds, visitor, etc. '----------------------------------------------------------------------------------------------------------- Imports System.IO Public Class TestWriter Inherits WriteUtils Private ReadOnly _checksum As String Private _writer As TextWriter 'output is sent here. Private Const s_externalSourceDirectiveString As String = "ExternalSourceDirective" ' Initialize the class with the parse tree to write. Public Sub New(parseTree As ParseTree, checksum As String) MyBase.New(parseTree) _checksum = checksum End Sub ' Write out the code defining the tree to the give file. Public Sub WriteTestCode(writer As TextWriter) _writer = writer GenerateFile() End Sub Private Sub GenerateFile() _writer.WriteLine("' Tests for parse trees.") _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub Private Sub GenerateNamespace() _writer.WriteLine() _writer.WriteLine("Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests") _writer.WriteLine() _writer.WriteLine("Partial Public Class GeneratedTests") _writer.WriteLine() _writer.WriteLine("#region ""Green Factory Calls""") GenerateFactoryCalls(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Green Factory Tests""") GenerateFactoryCallTests(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Green Rewriter Tests""") GenerateRewriterTests(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Green Visitor Tests""") GenerateVisitorTests(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Red Factory Calls""") GenerateFactoryCalls(False) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Red Factory Tests""") GenerateFactoryCallTests(False) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Red Rewriter Tests""") GenerateRewriterTests(False) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("End Class") _writer.WriteLine("End Namespace") End Sub Private Sub GenerateFactoryCalls(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then If Not nodeStructure.Name = "KeywordSyntax" AndAlso Not nodeStructure.Name = "PunctuationSyntax" Then GenerateFactoryCall(isGreen, nodeStructure) End If End If Next End Sub Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateFactoryCall(isGreen, nodeStructure, kind) Next 'If nodeStructure.NodeKinds.Count > 1 Then ' GenerateFactoryCall(isGreen, nodeStructure, Nothing) 'End If End Sub Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name = "AttributeTarget" AndAlso Not isGreen Then Dim x = 0 End If If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim namespacePrefix As String = If(isGreen, "InternalSyntax.", String.Empty) _writer.Write(" Private Shared Function ") Dim functionName As String = If(nodeKind Is Nothing, FactoryName(nodeStructure), FactoryName(nodeKind)) If isGreen Then _writer.Write("GenerateGreen" + functionName) Else _writer.Write("GenerateRed" + functionName) End If If isGreen Then _writer.WriteLine("() As " + namespacePrefix + nodeStructure.Name) Else If nodeStructure.IsToken Then _writer.WriteLine("() As SyntaxToken") ElseIf nodeStructure.IsTrivia Then _writer.WriteLine("() As SyntaxTrivia") Else _writer.WriteLine("() As {0}", StructureTypeName(nodeStructure)) End If End If Dim first As Boolean = True Dim callTokens As List(Of String) = New List(Of String)() Dim anePositions As List(Of Integer) = New List(Of Integer)() Dim aePositions As List(Of Integer) = New List(Of Integer)() Dim KindNonePositions As List(Of Integer) = New List(Of Integer)() Dim currentLine = 1 If nodeKind Is Nothing Then callTokens.Add(namespacePrefix + "SyntaxFactory." + nodeStructure.Name + "(") Else callTokens.Add(namespacePrefix + "SyntaxFactory." + nodeKind.Name + "(") End If If nodeStructure.IsToken Then If isGreen Then If nodeStructure.IsTerminal Then callTokens.Add("String.Empty") first = False End If Else If Not first Then callTokens.Add(", ") first = False callTokens.Add(namespacePrefix + "SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") 'If nodeStructure.Name.Contains("Xml") Then ' callTokens.Add("String.Empty") ' first = False 'End If If nodeKind.Name.EndsWith("LiteralToken", StringComparison.Ordinal) OrElse nodeKind.Name.EndsWith("XmlNameToken", StringComparison.Ordinal) OrElse nodeKind.Name.EndsWith("DocumentationCommentLineBreakToken", StringComparison.Ordinal) OrElse nodeKind.Name = "InterpolatedStringTextToken" _ Then If Not first Then callTokens.Add(", ") callTokens.Add("String.Empty") first = False End If End If Dim fields = GetAllFieldsOfStructure(nodeStructure) For Each field In fields If Not first Then callTokens.Add(", ") first = False Dim fieldType = FieldTypeRef(field) callTokens.Add(GetInitValueForType(fieldType)) Next If Not first Then callTokens.Add(", ") first = False If isGreen Then callTokens.Add(namespacePrefix + "SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""), ") callTokens.Add(namespacePrefix + "SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") Else callTokens.Add(namespacePrefix + "SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" "")))") End If If isGreen Then _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() Else _writer.WriteLine(" Dim exceptionTest as boolean = false") For exceptionChecks = 0 To anePositions.Count - 1 _writer.WriteLine(" Try") For i = 0 To callTokens.Count - 1 If (i <> anePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("Nothing") End If Next _writer.WriteLine(" catch e as ArgumentNullException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine(" exceptionTest = false") _writer.WriteLine() Next ' quick hack to cover more code in keyword factories ... If nodeStructure.IsTerminal AndAlso Not nodeStructure.IsTrivia AndAlso nodeStructure.Name = "KeywordSyntax" Then _writer.Write(" Dim node1 = ") For i = 0 To callTokens.Count - 1 _writer.Write(callTokens(i)) If i = 0 Then _writer.Write("String.Empty, ") Next i _writer.WriteLine() _writer.Write(" dim node2 = ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() _writer.WriteLine(" Debug.Assert(node1.GetText() = String.Empty)") _writer.WriteLine(" Debug.Assert(node2.GetText() <> String.Empty)") _writer.WriteLine() ' make parameter = nothing to cause exceptions _writer.WriteLine(" Try") _writer.WriteLine(" exceptionTest = false") For i = 0 To callTokens.Count - 1 _writer.Write(callTokens(i)) If i = 0 Then _writer.Write("Nothing, ") Next i _writer.WriteLine() _writer.WriteLine(" catch e as ArgumentNullException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine() _writer.WriteLine(" return node2") Else _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() End If End If Else Dim children = GetAllFactoryChildrenOfStructure(nodeStructure) If nodeStructure.IsTrivia Then callTokens.Add("String.Empty") anePositions.Add(callTokens.Count - 1) first = False End If For Each child In children If Not first Then callTokens.Add(", ") End If If child.IsOptional Then ' Hack: remove when the factory methods have been fixed to not contain overloads. If nodeStructure.Name = "MemberAccessExpressionSyntax" Then If first Then callTokens.Add(String.Format("CType(Nothing, {0}{1})", namespacePrefix, ChildFieldTypeRef(child))) End If Else callTokens.Add("Nothing") End If ' TODO: remove first = False Continue For End If ' TODO: move up. first = False Dim childNodeKind As ParseNodeKind = If(Not child Is Nothing, TryCast(child.ChildKind, ParseNodeKind), Nothing) If TypeOf child.ChildKind Is List(Of ParseNodeKind) Then childNodeKind = child.ChildKind(nodeKind.Name) End If If childNodeKind Is Nothing Then childNodeKind = DirectCast(child.ChildKind, List(Of ParseNodeKind)).Item(0) End If If child.IsList AndAlso child.IsSeparated Then Dim childKindStructure = child.ParseTree.NodeStructures(childNodeKind.StructureId) childKindStructure = If(Not childKindStructure.ParentStructure Is Nothing, childKindStructure.ParentStructure, childKindStructure) callTokens.Add("New " + ChildFactoryTypeRef(nodeStructure, child, isGreen, True) + "()") Else Dim structureOfchild = child.ParseTree.NodeStructures(childNodeKind.StructureId) If structureOfchild.Name = "PunctuationSyntax" OrElse structureOfchild.Name = "KeywordSyntax" Then If isGreen Then callTokens.Add("new InternalSyntax." + structureOfchild.Name + "(") callTokens.Add("SyntaxKind." + childNodeKind.Name + ", String.Empty, Nothing, Nothing)") Else Dim token = "SyntaxFactory.Token(SyntaxKind." + childNodeKind.Name + ")" If child.IsList Then token = "SyntaxTokenList.Create(" & token & ")" End If callTokens.Add(token) ' add none kind here If Not TypeOf child.ChildKind Is List(Of ParseNodeKind) Then If child.IsOptional Then KindNonePositions.Add(callTokens.Count - 1) End If Else If Not child.IsList Then aePositions.Add(callTokens.Count - 1) End If End If End If Else If isGreen Then callTokens.Add("GenerateGreen" + FactoryName(childNodeKind) + "()") Else Dim result = "GenerateRed" + FactoryName(childNodeKind) + "()" If structureOfchild.IsToken AndAlso child.IsList Then result = "SyntaxTokenList.Create(" & result & ")" ElseIf child.IsSeparated Then result = String.Format("SyntaxFactory.SingletonSeparatedList(Of {0}({1})", BaseTypeReference(child), result) ElseIf child.IsList Then result = String.Format("SyntaxFactory.SingletonList(Of {0})({1})", BaseTypeReference(child), result) End If callTokens.Add(result) End If End If If Not KindTypeStructure(child.ChildKind).IsToken AndAlso Not child.IsList Then anePositions.Add(callTokens.Count - 1) ElseIf KindTypeStructure(child.ChildKind).IsToken And Not child.IsList Then aePositions.Add(callTokens.Count - 1) End If End If Next callTokens.Add(")") ' TODO: remove extra conditions If isGreen OrElse nodeStructure.Name = "CaseBlockSyntax" OrElse nodeStructure.Name = "IfPartSyntax" OrElse nodeStructure.Name = "MultiLineIfBlockSyntax" Then _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() Else _writer.WriteLine(" Dim exceptionTest as boolean = false") For exceptionChecks = 0 To anePositions.Count - 1 _writer.WriteLine(" Try") _writer.Write(" ") For i = 0 To callTokens.Count - 1 If (i <> anePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("Nothing") End If Next _writer.WriteLine() _writer.WriteLine(" catch e as ArgumentNullException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine(" exceptionTest = false") _writer.WriteLine() Next For exceptionChecks = 0 To aePositions.Count - 1 _writer.WriteLine(" Try") _writer.Write(" ") For i = 0 To callTokens.Count - 1 If (i <> aePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("SyntaxFactory.Token(SyntaxKind.ExternalSourceKeyword)") ' this syntaxtoken should not be legal anywhere in the tests End If Next _writer.WriteLine() _writer.WriteLine(" catch e as ArgumentException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine(" exceptionTest = false") _writer.WriteLine() Next For exceptionChecks = 0 To KindNonePositions.Count - 1 _writer.Write(" ") For i = 0 To callTokens.Count - 1 If (i <> KindNonePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("New SyntaxToken(Nothing, New InternalSyntax.KeywordSyntax(SyntaxKind.None, Nothing, Nothing, """", Nothing, Nothing), 0, 0)") End If Next _writer.WriteLine() _writer.WriteLine() Next _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() End If End If _writer.WriteLine(" End Function") _writer.WriteLine() End Sub Private Sub GenerateFactoryCallTests(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then If Not nodeStructure.Name = "KeywordSyntax" AndAlso Not nodeStructure.Name = "PunctuationSyntax" Then GenerateFactoryCallTest(isGreen, nodeStructure) End If End If Next End Sub Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateFactoryCallTest(isGreen, nodeStructure, kind) Next End Sub Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim funcNamePart = If(isGreen, "Green", "Red") _writer.WriteLine(" <Fact>") _writer.Write(" Public Sub ") _writer.Write("Test{0}{1}", funcNamePart, FactoryName(nodeKind)) _writer.WriteLine("()") _writer.WriteLine(" dim objectUnderTest = Generate{0}{1}()", funcNamePart, FactoryName(nodeKind)) 'Dim children = GetAllChildrenOfStructure(nodeStructure) If isGreen Then _writer.WriteLine(" AttachAndCheckDiagnostics(objectUnderTest)") Else Dim withStat As String = Nothing For Each child In GetAllChildrenOfStructure(nodeStructure) If Not child.IsOptional Then _writer.WriteLine(" Assert.NotNull(objectUnderTest.{0})", LowerFirstCharacter(child.Name)) End If withStat += String.Format(".With{0}(objectUnderTest.{0})", child.Name) Next If (withStat IsNot Nothing) Then _writer.WriteLine(" Dim withObj = objectUnderTest{0}", withStat) _writer.WriteLine(" Assert.Equal(withobj, objectUnderTest)") End If End If _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateRewriterTests(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then GenerateRewriterTest(isGreen, nodeStructure) End If Next End Sub Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateRewriterTest(isGreen, nodeStructure, kind) Next End Sub Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim funcNamePart = If(isGreen, "Green", "Red") _writer.WriteLine(" <Fact>") _writer.Write(" Public Sub ") _writer.Write("Test{0}{1}Rewriter", funcNamePart, FactoryName(nodeKind)) _writer.WriteLine("()") _writer.WriteLine(" dim oldNode = Generate{0}{1}()", funcNamePart, FactoryName(nodeKind)) _writer.WriteLine(" Dim rewriter = New {0}IdentityRewriter()", funcNamePart) _writer.WriteLine(" Dim newNode = rewriter.Visit(oldNode)") _writer.WriteLine(" Assert.Equal(oldNode, newNode)") _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateVisitorTests(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then GenerateVisitorTest(isGreen, nodeStructure) End If Next End Sub Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateVisitorTest(isGreen, nodeStructure, kind) Next End Sub Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim funcNamePart = If(isGreen, "Green", "Red") _writer.WriteLine(" <Fact>") _writer.Write(" Public Sub ") _writer.Write("Test" + funcNamePart + FactoryName(nodeKind) + "Visitor") _writer.WriteLine("()") _writer.WriteLine(" Dim oldNode = Generate" + funcNamePart + FactoryName(nodeKind) + "()") _writer.WriteLine(" Dim visitor = New " + funcNamePart + "NodeVisitor()") _writer.WriteLine(" visitor.Visit(oldNode)") _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Public Function GetInitValueForType(fieldType As String) As String Select Case fieldType Case "Integer" Return "23" Case "String" Return """Bar""" Case "Char" Return """E""C" Case "DateTime" Return "New DateTime(2008,11,04)" Case "System.Decimal" Return "42" Case "TypeCharacter" Return "TypeCharacter.DecimalLiteral" Case "SyntaxKind" Return "SyntaxKind.IdentifierName" Case Else Return "Unknown Type" End Select End Function Public Sub AddHandwrittenFactoryCall(baseType As String) Select Case baseType Case "IdentifierTokenSyntax" _writer.Write("new InternalSyntax.SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, ""text"",") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""), ") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") Case "IntegerLiteralTokenSyntax" _writer.Write("new InternalSyntax.IntegerLiteralToken(""42"", LiteralBase.Decimal, TypeCharacter.None, 42,") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""), ") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") End Select 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. '----------------------------------------------------------------------------------------------------------- ' This is the code that actually outputs the VB code that defines the tree. It is passed a read and validated ' ParseTree, and outputs the code to defined the node classes for that tree, and also additional data ' structures like the kinds, visitor, etc. '----------------------------------------------------------------------------------------------------------- Imports System.IO Public Class TestWriter Inherits WriteUtils Private ReadOnly _checksum As String Private _writer As TextWriter 'output is sent here. Private Const s_externalSourceDirectiveString As String = "ExternalSourceDirective" ' Initialize the class with the parse tree to write. Public Sub New(parseTree As ParseTree, checksum As String) MyBase.New(parseTree) _checksum = checksum End Sub ' Write out the code defining the tree to the give file. Public Sub WriteTestCode(writer As TextWriter) _writer = writer GenerateFile() End Sub Private Sub GenerateFile() _writer.WriteLine("' Tests for parse trees.") _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub Private Sub GenerateNamespace() _writer.WriteLine() _writer.WriteLine("Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests") _writer.WriteLine() _writer.WriteLine("Partial Public Class GeneratedTests") _writer.WriteLine() _writer.WriteLine("#region ""Green Factory Calls""") GenerateFactoryCalls(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Green Factory Tests""") GenerateFactoryCallTests(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Green Rewriter Tests""") GenerateRewriterTests(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Green Visitor Tests""") GenerateVisitorTests(True) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Red Factory Calls""") GenerateFactoryCalls(False) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Red Factory Tests""") GenerateFactoryCallTests(False) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("#region ""Red Rewriter Tests""") GenerateRewriterTests(False) _writer.WriteLine("#end region") _writer.WriteLine() _writer.WriteLine("End Class") _writer.WriteLine("End Namespace") End Sub Private Sub GenerateFactoryCalls(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then If Not nodeStructure.Name = "KeywordSyntax" AndAlso Not nodeStructure.Name = "PunctuationSyntax" Then GenerateFactoryCall(isGreen, nodeStructure) End If End If Next End Sub Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateFactoryCall(isGreen, nodeStructure, kind) Next 'If nodeStructure.NodeKinds.Count > 1 Then ' GenerateFactoryCall(isGreen, nodeStructure, Nothing) 'End If End Sub Private Sub GenerateFactoryCall(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name = "AttributeTarget" AndAlso Not isGreen Then Dim x = 0 End If If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim namespacePrefix As String = If(isGreen, "InternalSyntax.", String.Empty) _writer.Write(" Private Shared Function ") Dim functionName As String = If(nodeKind Is Nothing, FactoryName(nodeStructure), FactoryName(nodeKind)) If isGreen Then _writer.Write("GenerateGreen" + functionName) Else _writer.Write("GenerateRed" + functionName) End If If isGreen Then _writer.WriteLine("() As " + namespacePrefix + nodeStructure.Name) Else If nodeStructure.IsToken Then _writer.WriteLine("() As SyntaxToken") ElseIf nodeStructure.IsTrivia Then _writer.WriteLine("() As SyntaxTrivia") Else _writer.WriteLine("() As {0}", StructureTypeName(nodeStructure)) End If End If Dim first As Boolean = True Dim callTokens As List(Of String) = New List(Of String)() Dim anePositions As List(Of Integer) = New List(Of Integer)() Dim aePositions As List(Of Integer) = New List(Of Integer)() Dim KindNonePositions As List(Of Integer) = New List(Of Integer)() Dim currentLine = 1 If nodeKind Is Nothing Then callTokens.Add(namespacePrefix + "SyntaxFactory." + nodeStructure.Name + "(") Else callTokens.Add(namespacePrefix + "SyntaxFactory." + nodeKind.Name + "(") End If If nodeStructure.IsToken Then If isGreen Then If nodeStructure.IsTerminal Then callTokens.Add("String.Empty") first = False End If Else If Not first Then callTokens.Add(", ") first = False callTokens.Add(namespacePrefix + "SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") 'If nodeStructure.Name.Contains("Xml") Then ' callTokens.Add("String.Empty") ' first = False 'End If If nodeKind.Name.EndsWith("LiteralToken", StringComparison.Ordinal) OrElse nodeKind.Name.EndsWith("XmlNameToken", StringComparison.Ordinal) OrElse nodeKind.Name.EndsWith("DocumentationCommentLineBreakToken", StringComparison.Ordinal) OrElse nodeKind.Name = "InterpolatedStringTextToken" _ Then If Not first Then callTokens.Add(", ") callTokens.Add("String.Empty") first = False End If End If Dim fields = GetAllFieldsOfStructure(nodeStructure) For Each field In fields If Not first Then callTokens.Add(", ") first = False Dim fieldType = FieldTypeRef(field) callTokens.Add(GetInitValueForType(fieldType)) Next If Not first Then callTokens.Add(", ") first = False If isGreen Then callTokens.Add(namespacePrefix + "SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""), ") callTokens.Add(namespacePrefix + "SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") Else callTokens.Add(namespacePrefix + "SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" "")))") End If If isGreen Then _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() Else _writer.WriteLine(" Dim exceptionTest as boolean = false") For exceptionChecks = 0 To anePositions.Count - 1 _writer.WriteLine(" Try") For i = 0 To callTokens.Count - 1 If (i <> anePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("Nothing") End If Next _writer.WriteLine(" catch e as ArgumentNullException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine(" exceptionTest = false") _writer.WriteLine() Next ' quick hack to cover more code in keyword factories ... If nodeStructure.IsTerminal AndAlso Not nodeStructure.IsTrivia AndAlso nodeStructure.Name = "KeywordSyntax" Then _writer.Write(" Dim node1 = ") For i = 0 To callTokens.Count - 1 _writer.Write(callTokens(i)) If i = 0 Then _writer.Write("String.Empty, ") Next i _writer.WriteLine() _writer.Write(" dim node2 = ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() _writer.WriteLine(" Debug.Assert(node1.GetText() = String.Empty)") _writer.WriteLine(" Debug.Assert(node2.GetText() <> String.Empty)") _writer.WriteLine() ' make parameter = nothing to cause exceptions _writer.WriteLine(" Try") _writer.WriteLine(" exceptionTest = false") For i = 0 To callTokens.Count - 1 _writer.Write(callTokens(i)) If i = 0 Then _writer.Write("Nothing, ") Next i _writer.WriteLine() _writer.WriteLine(" catch e as ArgumentNullException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine() _writer.WriteLine(" return node2") Else _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() End If End If Else Dim children = GetAllFactoryChildrenOfStructure(nodeStructure) If nodeStructure.IsTrivia Then callTokens.Add("String.Empty") anePositions.Add(callTokens.Count - 1) first = False End If For Each child In children If Not first Then callTokens.Add(", ") End If If child.IsOptional Then ' Hack: remove when the factory methods have been fixed to not contain overloads. If nodeStructure.Name = "MemberAccessExpressionSyntax" Then If first Then callTokens.Add(String.Format("CType(Nothing, {0}{1})", namespacePrefix, ChildFieldTypeRef(child))) End If Else callTokens.Add("Nothing") End If ' TODO: remove first = False Continue For End If ' TODO: move up. first = False Dim childNodeKind As ParseNodeKind = If(Not child Is Nothing, TryCast(child.ChildKind, ParseNodeKind), Nothing) If TypeOf child.ChildKind Is List(Of ParseNodeKind) Then childNodeKind = child.ChildKind(nodeKind.Name) End If If childNodeKind Is Nothing Then childNodeKind = DirectCast(child.ChildKind, List(Of ParseNodeKind)).Item(0) End If If child.IsList AndAlso child.IsSeparated Then Dim childKindStructure = child.ParseTree.NodeStructures(childNodeKind.StructureId) childKindStructure = If(Not childKindStructure.ParentStructure Is Nothing, childKindStructure.ParentStructure, childKindStructure) callTokens.Add("New " + ChildFactoryTypeRef(nodeStructure, child, isGreen, True) + "()") Else Dim structureOfchild = child.ParseTree.NodeStructures(childNodeKind.StructureId) If structureOfchild.Name = "PunctuationSyntax" OrElse structureOfchild.Name = "KeywordSyntax" Then If isGreen Then callTokens.Add("new InternalSyntax." + structureOfchild.Name + "(") callTokens.Add("SyntaxKind." + childNodeKind.Name + ", String.Empty, Nothing, Nothing)") Else Dim token = "SyntaxFactory.Token(SyntaxKind." + childNodeKind.Name + ")" If child.IsList Then token = "SyntaxTokenList.Create(" & token & ")" End If callTokens.Add(token) ' add none kind here If Not TypeOf child.ChildKind Is List(Of ParseNodeKind) Then If child.IsOptional Then KindNonePositions.Add(callTokens.Count - 1) End If Else If Not child.IsList Then aePositions.Add(callTokens.Count - 1) End If End If End If Else If isGreen Then callTokens.Add("GenerateGreen" + FactoryName(childNodeKind) + "()") Else Dim result = "GenerateRed" + FactoryName(childNodeKind) + "()" If structureOfchild.IsToken AndAlso child.IsList Then result = "SyntaxTokenList.Create(" & result & ")" ElseIf child.IsSeparated Then result = String.Format("SyntaxFactory.SingletonSeparatedList(Of {0}({1})", BaseTypeReference(child), result) ElseIf child.IsList Then result = String.Format("SyntaxFactory.SingletonList(Of {0})({1})", BaseTypeReference(child), result) End If callTokens.Add(result) End If End If If Not KindTypeStructure(child.ChildKind).IsToken AndAlso Not child.IsList Then anePositions.Add(callTokens.Count - 1) ElseIf KindTypeStructure(child.ChildKind).IsToken And Not child.IsList Then aePositions.Add(callTokens.Count - 1) End If End If Next callTokens.Add(")") ' TODO: remove extra conditions If isGreen OrElse nodeStructure.Name = "CaseBlockSyntax" OrElse nodeStructure.Name = "IfPartSyntax" OrElse nodeStructure.Name = "MultiLineIfBlockSyntax" Then _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() Else _writer.WriteLine(" Dim exceptionTest as boolean = false") For exceptionChecks = 0 To anePositions.Count - 1 _writer.WriteLine(" Try") _writer.Write(" ") For i = 0 To callTokens.Count - 1 If (i <> anePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("Nothing") End If Next _writer.WriteLine() _writer.WriteLine(" catch e as ArgumentNullException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine(" exceptionTest = false") _writer.WriteLine() Next For exceptionChecks = 0 To aePositions.Count - 1 _writer.WriteLine(" Try") _writer.Write(" ") For i = 0 To callTokens.Count - 1 If (i <> aePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("SyntaxFactory.Token(SyntaxKind.ExternalSourceKeyword)") ' this syntaxtoken should not be legal anywhere in the tests End If Next _writer.WriteLine() _writer.WriteLine(" catch e as ArgumentException") _writer.WriteLine(" exceptionTest = true") _writer.WriteLine(" End Try") _writer.WriteLine(" Debug.Assert(exceptionTest)") _writer.WriteLine(" exceptionTest = false") _writer.WriteLine() Next For exceptionChecks = 0 To KindNonePositions.Count - 1 _writer.Write(" ") For i = 0 To callTokens.Count - 1 If (i <> KindNonePositions(exceptionChecks)) Then _writer.Write(callTokens(i)) Else _writer.Write("New SyntaxToken(Nothing, New InternalSyntax.KeywordSyntax(SyntaxKind.None, Nothing, Nothing, """", Nothing, Nothing), 0, 0)") End If Next _writer.WriteLine() _writer.WriteLine() Next _writer.Write(" return ") callTokens.ForEach(AddressOf _writer.Write) _writer.WriteLine() End If End If _writer.WriteLine(" End Function") _writer.WriteLine() End Sub Private Sub GenerateFactoryCallTests(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory Then If Not nodeStructure.Name = "KeywordSyntax" AndAlso Not nodeStructure.Name = "PunctuationSyntax" Then GenerateFactoryCallTest(isGreen, nodeStructure) End If End If Next End Sub Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateFactoryCallTest(isGreen, nodeStructure, kind) Next End Sub Private Sub GenerateFactoryCallTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim funcNamePart = If(isGreen, "Green", "Red") _writer.WriteLine(" <Fact>") _writer.Write(" Public Sub ") _writer.Write("Test{0}{1}", funcNamePart, FactoryName(nodeKind)) _writer.WriteLine("()") _writer.WriteLine(" dim objectUnderTest = Generate{0}{1}()", funcNamePart, FactoryName(nodeKind)) 'Dim children = GetAllChildrenOfStructure(nodeStructure) If isGreen Then _writer.WriteLine(" AttachAndCheckDiagnostics(objectUnderTest)") Else Dim withStat As String = Nothing For Each child In GetAllChildrenOfStructure(nodeStructure) If Not child.IsOptional Then _writer.WriteLine(" Assert.NotNull(objectUnderTest.{0})", LowerFirstCharacter(child.Name)) End If withStat += String.Format(".With{0}(objectUnderTest.{0})", child.Name) Next If (withStat IsNot Nothing) Then _writer.WriteLine(" Dim withObj = objectUnderTest{0}", withStat) _writer.WriteLine(" Assert.Equal(withobj, objectUnderTest)") End If End If _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateRewriterTests(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then GenerateRewriterTest(isGreen, nodeStructure) End If Next End Sub Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateRewriterTest(isGreen, nodeStructure, kind) Next End Sub Private Sub GenerateRewriterTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim funcNamePart = If(isGreen, "Green", "Red") _writer.WriteLine(" <Fact>") _writer.Write(" Public Sub ") _writer.Write("Test{0}{1}Rewriter", funcNamePart, FactoryName(nodeKind)) _writer.WriteLine("()") _writer.WriteLine(" dim oldNode = Generate{0}{1}()", funcNamePart, FactoryName(nodeKind)) _writer.WriteLine(" Dim rewriter = New {0}IdentityRewriter()", funcNamePart) _writer.WriteLine(" Dim newNode = rewriter.Visit(oldNode)") _writer.WriteLine(" Assert.Equal(oldNode, newNode)") _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Private Sub GenerateVisitorTests(isGreen As Boolean) For Each nodeStructure In _parseTree.NodeStructures.Values If Not nodeStructure.Abstract AndAlso Not nodeStructure.NoFactory AndAlso Not nodeStructure.IsToken AndAlso Not nodeStructure.IsTrivia Then GenerateVisitorTest(isGreen, nodeStructure) End If Next End Sub Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure) For Each kind In nodeStructure.NodeKinds GenerateVisitorTest(isGreen, nodeStructure, kind) Next End Sub Private Sub GenerateVisitorTest(isGreen As Boolean, nodeStructure As ParseNodeStructure, nodeKind As ParseNodeKind) If nodeKind.Name.Contains(s_externalSourceDirectiveString) Then Return ' check for fix End If Dim funcNamePart = If(isGreen, "Green", "Red") _writer.WriteLine(" <Fact>") _writer.Write(" Public Sub ") _writer.Write("Test" + funcNamePart + FactoryName(nodeKind) + "Visitor") _writer.WriteLine("()") _writer.WriteLine(" Dim oldNode = Generate" + funcNamePart + FactoryName(nodeKind) + "()") _writer.WriteLine(" Dim visitor = New " + funcNamePart + "NodeVisitor()") _writer.WriteLine(" visitor.Visit(oldNode)") _writer.WriteLine(" End Sub") _writer.WriteLine() End Sub Public Function GetInitValueForType(fieldType As String) As String Select Case fieldType Case "Integer" Return "23" Case "String" Return """Bar""" Case "Char" Return """E""C" Case "DateTime" Return "New DateTime(2008,11,04)" Case "System.Decimal" Return "42" Case "TypeCharacter" Return "TypeCharacter.DecimalLiteral" Case "SyntaxKind" Return "SyntaxKind.IdentifierName" Case Else Return "Unknown Type" End Select End Function Public Sub AddHandwrittenFactoryCall(baseType As String) Select Case baseType Case "IdentifierTokenSyntax" _writer.Write("new InternalSyntax.SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, ""text"",") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""), ") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") Case "IntegerLiteralTokenSyntax" _writer.Write("new InternalSyntax.IntegerLiteralToken(""42"", LiteralBase.Decimal, TypeCharacter.None, 42,") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""), ") _writer.Write("InternalSyntax.SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "" ""))") End Select End Sub End Class
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class VisualBasicTriviaFormatter Inherits AbstractTriviaFormatter Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia("_") Private _newLine As SyntaxTrivia Private _succeeded As Boolean = True Public Sub New(context As FormattingContext, formattingRules As ChainedFormattingRules, token1 As SyntaxToken, token2 As SyntaxToken, originalString As String, lineBreaks As Integer, spaces As Integer) MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces) End Sub Protected Overrides Function Succeeded() As Boolean Return _succeeded End Function Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.WhitespaceTrivia End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsWhitespace(ch As Char) As Boolean Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch) End Function Protected Overrides Function IsNewLine(ch As Char) As Boolean Return SyntaxFacts.IsNewLine(ch) End Function Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Protected Overrides Function CreateEndOfLine() As SyntaxTrivia If _newLine = Nothing Then Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine) _newLine = SyntaxFactory.EndOfLine(text) End If Return _newLine End Function Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule ' line continuation If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1) End If If IsStartOrEndOfFile(trivia1, trivia2) Then Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0) End If ' :: case If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : after : token If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : [token] If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.ColonTrivia OrElse trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If ' [trivia] [whitespace] [token] case If trivia2.Kind = SyntaxKind.None Then Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing If insertNewLine Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' preprocessor case If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then ' if this is the first line of the file, don't put extra line 1 Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None) Dim lines = If(firstLine, 0, 1) Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0) End If ' comment before a Case Statement case If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then Return LineColumnRule.Preserve End If ' comment case If trivia2.Kind = SyntaxKind.CommentTrivia OrElse trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then ' [token] [whitespace] [trivia] case If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' skipped tokens If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then _succeeded = False End If Return LineColumnRule.Preserve End Function Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean Return False End Function Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then trivia = FormatLineContinuationTrivia(trivia) End If changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then Dim lineContinuation = FormatLineContinuationTrivia(trivia) If trivia <> lineContinuation Then changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString())) End If Return GetLineColumnDelta(lineColumn, lineContinuation) End If Return GetLineColumnDelta(lineColumn, trivia) End Function Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then Return _lineContinuationTrivia End If Return trivia End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) changes.Add(formattedTrivia) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) changes.Add(docComment) Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia( trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) If result.GetTextChanges(cancellationToken).Count = 0 Then Return GetLineColumnDelta(lineColumn, trivia) End If changes.AddRange(result.GetTextChanges(cancellationToken)) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) If docComment <> trivia Then changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString())) End If Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart) Dim text = trivia.ToFullString() ' When the doc comment is parsed from source, even if it is only one ' line long, the end-of-line will get included into the trivia text. ' If the doc comment was parsed from a text fragment, there may not be ' an end-of-line at all. We need to trim the end before we check the ' number of line breaks in the text. #If NETCOREAPP Then Dim textWithoutFinalNewLine = text.TrimEnd() #Else Dim textWithoutFinalNewLine = text.TrimEnd(Nothing) #End If If Not textWithoutFinalNewLine.ContainsLineBreak() Then Return trivia End If Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment( forceIndentation:=True, indentation:=indentation, indentationDelta:=0, useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs), tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize), newLine:=Me.Options.GetOption(FormattingOptions2.NewLine)) If text = singlelineDocComments Then Return trivia End If Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments) Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1) Return singlelineDocCommentTrivia.ElementAt(0) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class VisualBasicTriviaFormatter Inherits AbstractTriviaFormatter Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia("_") Private _newLine As SyntaxTrivia Private _succeeded As Boolean = True Public Sub New(context As FormattingContext, formattingRules As ChainedFormattingRules, token1 As SyntaxToken, token2 As SyntaxToken, originalString As String, lineBreaks As Integer, spaces As Integer) MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces) End Sub Protected Overrides Function Succeeded() As Boolean Return _succeeded End Function Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.WhitespaceTrivia End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsWhitespace(ch As Char) As Boolean Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch) End Function Protected Overrides Function IsNewLine(ch As Char) As Boolean Return SyntaxFacts.IsNewLine(ch) End Function Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Protected Overrides Function CreateEndOfLine() As SyntaxTrivia If _newLine = Nothing Then Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine) _newLine = SyntaxFactory.EndOfLine(text) End If Return _newLine End Function Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule ' line continuation If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1) End If If IsStartOrEndOfFile(trivia1, trivia2) Then Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0) End If ' :: case If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : after : token If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : [token] If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.ColonTrivia OrElse trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If ' [trivia] [whitespace] [token] case If trivia2.Kind = SyntaxKind.None Then Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing If insertNewLine Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' preprocessor case If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then ' if this is the first line of the file, don't put extra line 1 Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None) Dim lines = If(firstLine, 0, 1) Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0) End If ' comment before a Case Statement case If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then Return LineColumnRule.Preserve End If ' comment case If trivia2.Kind = SyntaxKind.CommentTrivia OrElse trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then ' [token] [whitespace] [trivia] case If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' skipped tokens If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then _succeeded = False End If Return LineColumnRule.Preserve End Function Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean Return False End Function Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then trivia = FormatLineContinuationTrivia(trivia) End If changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then Dim lineContinuation = FormatLineContinuationTrivia(trivia) If trivia <> lineContinuation Then changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString())) End If Return GetLineColumnDelta(lineColumn, lineContinuation) End If Return GetLineColumnDelta(lineColumn, trivia) End Function Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then Return _lineContinuationTrivia End If Return trivia End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) changes.Add(formattedTrivia) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) changes.Add(docComment) Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia( trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) If result.GetTextChanges(cancellationToken).Count = 0 Then Return GetLineColumnDelta(lineColumn, trivia) End If changes.AddRange(result.GetTextChanges(cancellationToken)) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) If docComment <> trivia Then changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString())) End If Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart) Dim text = trivia.ToFullString() ' When the doc comment is parsed from source, even if it is only one ' line long, the end-of-line will get included into the trivia text. ' If the doc comment was parsed from a text fragment, there may not be ' an end-of-line at all. We need to trim the end before we check the ' number of line breaks in the text. #If NETCOREAPP Then Dim textWithoutFinalNewLine = text.TrimEnd() #Else Dim textWithoutFinalNewLine = text.TrimEnd(Nothing) #End If If Not textWithoutFinalNewLine.ContainsLineBreak() Then Return trivia End If Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment( forceIndentation:=True, indentation:=indentation, indentationDelta:=0, useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs), tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize), newLine:=Me.Options.GetOption(FormattingOptions2.NewLine)) If text = singlelineDocComments Then Return trivia End If Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments) Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1) Return singlelineDocCommentTrivia.ElementAt(0) End Function End Class End Namespace
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreation.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.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode ' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them ' two times. Dim objectInitializer = node.InitializerOpt node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type) Dim ctor = node.ConstructorOpt Dim result As BoundExpression = node If ctor IsNot Nothing Then Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing result = node.Update(ctor, RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False), node.DefaultArguments, Nothing, ctor.ContainingType) If Not temporaries.IsDefault Then result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack) End If ' If a coclass was instantiated, convert the class to the interface type. If node.Type.IsInterfaceType() Then Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType)) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo) Debug.Assert(Conversions.ConversionExists(conv)) _diagnostics.Add(result, useSiteInfo) result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing) Else Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type)) End If End If If objectInitializer IsNot Nothing Then Return VisitObjectCreationInitializer(objectInitializer, node, result) End If Return result End Function Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode ' For the NoPIA feature, we need to gather the GUID from the coclass, and ' generate the following: ' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType) ' ' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework), ' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID. Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) Dim newGuid As BoundExpression If ctor IsNot Nothing Then newGuid = factory.[New](ctor, factory.Literal(node.GuidString)) Else newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True), factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID)) Dim callGetTypeFromCLSID As BoundExpression If getTypeFromCLSID IsNot Nothing Then callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid) Else callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance) Dim rewrittenObjectCreation As BoundExpression If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type) Else rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True) End If If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then Return rewrittenObjectCreation End If Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation) End Function Private Function VisitObjectCreationInitializer( objectInitializer As BoundObjectInitializerExpressionBase, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) Else Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) End If End Function Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode ' Unlike C#, "New T()" is always rewritten as "Activator.CreateInstance<T>()", ' even if T is known to be a value type or reference type. This matches Dev10 VB. If _inExpressionLambda Then ' NOTE: If we are in expression lambda, we want to keep BoundNewT ' NOTE: node, but we need to rewrite initializers if any. If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, node, node) Else Return node End If End If Dim syntax = node.Syntax Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol) Dim result As BoundExpression Dim method As MethodSymbol = Nothing If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then Debug.Assert(method IsNot Nothing) method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter)) result = New BoundCall(syntax, method, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=typeParameter) Else result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True) End If If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, result, result) End If Return result End Function ''' <summary> ''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary. ''' E.g. the following code: ''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}} ''' gets rewritten to ''' Dim temp as CollectionType ''' temp = new CollectionType(param1) ''' temp.Add(1) ''' temp.Add(2, 3) ''' temp.Add(4, {5, 6, 7}) ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression ''' only represents the object creation expression with the initialization. ''' </summary> ''' <param name="node">The BoundCollectionInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions.</returns> Public Function RewriteCollectionInitializerExpression( node As BoundCollectionInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Debug.Assert(node.PlaceholderOpt IsNot Nothing) Dim expressionType = node.Type Dim syntaxNode = node.Syntax Dim tempLocalSymbol As LocalSymbol Dim tempLocal As BoundLocal Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance() Dim newPlaceholder As BoundWithLValueExpressionPlaceholder If _inExpressionLambda Then ' A temp is not needed for this case tempLocalSymbol = Nothing tempLocal = Nothing ' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to ' keep the double rewrite tracking happy. newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type) AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder) Else ' Create a temp symbol ' Dim temp as CollectionType ' Create assignment for the rewritten object ' creation expression to the temp ' temp = new CollectionType(param1) tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType) Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode, tempLocal, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) expressions.Add(temporaryAssignment) newPlaceholder = Nothing AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal) End If Dim initializerCount = node.Initializers.Length ' rewrite the invocation expressions and add them to the expression of the sequence ' temp.Add(...) For initializerIndex = 0 To initializerCount - 1 ' NOTE: if the method Add(...) is omitted we build a local which ' seems to be redundant, this will optimized out later ' by stack scheduler Dim initializer As BoundExpression = node.Initializers(initializerIndex) If Not IsOmittedBoundCall(initializer) Then expressions.Add(VisitExpressionNode(initializer)) End If Next RemovePlaceholderReplacement(node.PlaceholderOpt) If _inExpressionLambda Then Debug.Assert(tempLocalSymbol Is Nothing) Debug.Assert(tempLocal Is Nothing) ' NOTE: if inside expression lambda we rewrite the collection initializer ' NOTE: node and attach it back to object creation expression, it will be ' NOTE: rewritten later in ExpressionLambdaRewriter ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(newPlaceholder, expressions.ToImmutableAndFree(), node.Type)) Else Debug.Assert(tempLocalSymbol IsNot Nothing) Debug.Assert(tempLocal IsNot Nothing) Return New BoundSequence(syntaxNode, ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol), expressions.ToImmutableAndFree(), tempLocal.MakeRValue(), expressionType) End If End Function ''' <summary> ''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound ''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is ''' stored in the bound object member initializer node itself. ''' ''' E.g. the following code: ''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' Dim temp as RefTypeName ''' temp = new RefTypeName(param1) ''' temp.FieldName1 = 23 ''' temp.FieldName2 = temp.FieldName3 ''' temp.FieldName4 = x.FieldName1 ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression ''' only represents the object creation expression with the initialization. ''' ''' In a case where no temporary is used the following code: ''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' x = new ValueTypeName(param1) ''' x.FieldName1 = 23 ''' x.FieldName2 = x.FieldName3 ''' x.FieldName4 = x.FieldName1 ''' </summary> ''' <param name="node">The BoundObjectInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions, or a ''' bound statement list if no temporary should be used.</returns> Public Function RewriteObjectInitializerExpression( node As BoundObjectInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Dim targetObjectReference As BoundExpression Dim expressionType = node.Type Dim initializerCount = node.Initializers.Length Dim syntaxNode = node.Syntax Dim sequenceType As TypeSymbol Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol) Dim sequenceValueExpression As BoundExpression Debug.Assert(node.PlaceholderOpt IsNot Nothing) ' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially ' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to ' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments, ' NOTE: ExpressionLambdaRewriter will get rid of them ' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the ' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself If node.CreateTemporaryLocalForInitialization Then ' create temporary ' Dim temp as RefTypeName Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) sequenceType = expressionType sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol) targetObjectReference = If(_inExpressionLambda, DirectCast(node.PlaceholderOpt, BoundExpression), New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)) sequenceValueExpression = targetObjectReference.MakeRValue() AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference) Else ' Get the receiver for the current initialized variable in case of an "AsNew" declaration ' this is the only case where there might be no temporary needed. ' The replacement for this placeholder was added in VisitAsNewLocalDeclarations. targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt) sequenceType = GetSpecialType(SpecialType.System_Void) sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty sequenceValueExpression = Nothing End If Dim sequenceExpressions(initializerCount) As BoundExpression ' create assignment for object creation expression to temporary or variable declaration ' x = new TypeName(...) ' or ' temp = new TypeName(...) sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode, targetObjectReference, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) ' rewrite the assignment expressions and add them to the statement list ' x.FieldName = value expression ' or ' temp.FieldName = value expression For initializerIndex = 0 To initializerCount - 1 If _inExpressionLambda Then ' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part ' NOTE: will be kept unchanged to make sure we got proper symbol out of it Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator) Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing) sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left, assignment.LeftOnTheRightOpt, VisitExpressionNode(assignment.Right), True, assignment.Type) Else sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex)) End If Next If node.CreateTemporaryLocalForInitialization Then RemovePlaceholderReplacement(node.PlaceholderOpt) End If If _inExpressionLambda Then ' when converting object initializer inside expression lambdas we want to keep ' object initializer in object creation expression; we just store visited initializers ' back to the original object initializer and update the original object creation expression ' create new initializers Dim newInitializers(initializerCount - 1) As BoundExpression Dim errors As Boolean = False For index = 0 To initializerCount - 1 newInitializers(index) = sequenceExpressions(index + 1) Next ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(node.CreateTemporaryLocalForInitialization, node.PlaceholderOpt, newInitializers.AsImmutableOrNull(), node.Type)) End If Return New BoundSequence(syntaxNode, sequenceTemporaries, sequenceExpressions.AsImmutableOrNull, sequenceValueExpression, sequenceType) End Function Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression Select Case rewrittenObjectCreationExpression.Kind Case BoundKind.ObjectCreationExpression Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression) Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type) Case BoundKind.NewT Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT) Return newT.Update(rewrittenInitializer, newT.Type) Case BoundKind.Sequence ' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it ' NOTE: was probably wrapped with sequence which means that this case is not supported ' NOTE: inside expression lambdas. Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence) Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression) Return sequence.Update(sequence.Locals, sequence.SideEffects, ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer), sequence.Type) Case Else Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind) End Select 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.Diagnostics Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode ' save the object initializer away to rewrite them later on and set the initializers to nothing to not rewrite them ' two times. Dim objectInitializer = node.InitializerOpt node = node.Update(node.ConstructorOpt, node.Arguments, node.DefaultArguments, Nothing, node.Type) Dim ctor = node.ConstructorOpt Dim result As BoundExpression = node If ctor IsNot Nothing Then Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing result = node.Update(ctor, RewriteCallArguments(node.Arguments, ctor.Parameters, temporaries, copyBack, False), node.DefaultArguments, Nothing, ctor.ContainingType) If Not temporaries.IsDefault Then result = GenerateSequenceValueSideEffects(_currentMethodOrLambda, result, StaticCast(Of LocalSymbol).From(temporaries), copyBack) End If ' If a coclass was instantiated, convert the class to the interface type. If node.Type.IsInterfaceType() Then Debug.Assert(result.Type.Equals(DirectCast(node.Type, NamedTypeSymbol).CoClassType)) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conv As ConversionKind = Conversions.ClassifyDirectCastConversion(result.Type, node.Type, useSiteInfo) Debug.Assert(Conversions.ConversionExists(conv)) _diagnostics.Add(result, useSiteInfo) result = New BoundDirectCast(node.Syntax, result, conv, node.Type, Nothing) Else Debug.Assert(node.Type.IsSameTypeIgnoringAll(result.Type)) End If End If If objectInitializer IsNot Nothing Then Return VisitObjectCreationInitializer(objectInitializer, node, result) End If Return result End Function Public Overrides Function VisitNoPiaObjectCreationExpression(node As BoundNoPiaObjectCreationExpression) As BoundNode ' For the NoPIA feature, we need to gather the GUID from the coclass, and ' generate the following: ' DirectCast(System.Activator.CreateInstance(System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(New Guid(GUID))), IPiaType) ' ' If System.Runtime.InteropServices.Marshal.GetTypeFromCLSID is not available (older framework), ' System.Type.GetTypeFromCLSID() is used to get the type for the CLSID. Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) Dim ctor = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Guid__ctor) Dim newGuid As BoundExpression If ctor IsNot Nothing Then newGuid = factory.[New](ctor, factory.Literal(node.GuidString)) Else newGuid = New BoundBadExpression(node.Syntax, LookupResultKind.NotCreatable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim getTypeFromCLSID = If(factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, isOptional:=True), factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Type__GetTypeFromCLSID)) Dim callGetTypeFromCLSID As BoundExpression If getTypeFromCLSID IsNot Nothing Then callGetTypeFromCLSID = factory.Call(Nothing, getTypeFromCLSID, newGuid) Else callGetTypeFromCLSID = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim createInstance = factory.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Activator__CreateInstance) Dim rewrittenObjectCreation As BoundExpression If createInstance IsNot Nothing AndAlso Not createInstance.ReturnType.IsErrorType() Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conversion = Conversions.ClassifyDirectCastConversion(createInstance.ReturnType, node.Type, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenObjectCreation = New BoundDirectCast(node.Syntax, factory.Call(Nothing, createInstance, callGetTypeFromCLSID), conversion, node.Type) Else rewrittenObjectCreation = New BoundBadExpression(node.Syntax, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, node.Type, hasErrors:=True) End If If node.InitializerOpt Is Nothing OrElse node.InitializerOpt.HasErrors Then Return rewrittenObjectCreation End If Return VisitObjectCreationInitializer(node.InitializerOpt, node, rewrittenObjectCreation) End Function Private Function VisitObjectCreationInitializer( objectInitializer As BoundObjectInitializerExpressionBase, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode If objectInitializer.Kind = BoundKind.CollectionInitializerExpression Then Return RewriteCollectionInitializerExpression(DirectCast(objectInitializer, BoundCollectionInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) Else Return RewriteObjectInitializerExpression(DirectCast(objectInitializer, BoundObjectInitializerExpression), objectCreationExpression, rewrittenObjectCreationExpression) End If End Function Public Overrides Function VisitNewT(node As BoundNewT) As BoundNode ' Unlike C#, "New T()" is always rewritten as "Activator.CreateInstance<T>()", ' even if T is known to be a value type or reference type. This matches Dev10 VB. If _inExpressionLambda Then ' NOTE: If we are in expression lambda, we want to keep BoundNewT ' NOTE: node, but we need to rewrite initializers if any. If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, node, node) Else Return node End If End If Dim syntax = node.Syntax Dim typeParameter = DirectCast(node.Type, TypeParameterSymbol) Dim result As BoundExpression Dim method As MethodSymbol = Nothing If TryGetWellknownMember(method, WellKnownMember.System_Activator__CreateInstance_T, syntax) Then Debug.Assert(method IsNot Nothing) method = method.Construct(ImmutableArray.Create(Of TypeSymbol)(typeParameter)) result = New BoundCall(syntax, method, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=typeParameter) Else result = New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundExpression).Empty, typeParameter, hasErrors:=True) End If If node.InitializerOpt IsNot Nothing Then Return VisitObjectCreationInitializer(node.InitializerOpt, result, result) End If Return result End Function ''' <summary> ''' Rewrites a CollectionInitializerExpression to a list of Add calls and returns the temporary. ''' E.g. the following code: ''' Dim x As New CollectionType(param1) From {1, {2, 3}, {4, {5, 6, 7}}} ''' gets rewritten to ''' Dim temp as CollectionType ''' temp = new CollectionType(param1) ''' temp.Add(1) ''' temp.Add(2, 3) ''' temp.Add(4, {5, 6, 7}) ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundCollectionInitializerExpression ''' only represents the object creation expression with the initialization. ''' </summary> ''' <param name="node">The BoundCollectionInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions.</returns> Public Function RewriteCollectionInitializerExpression( node As BoundCollectionInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Debug.Assert(node.PlaceholderOpt IsNot Nothing) Dim expressionType = node.Type Dim syntaxNode = node.Syntax Dim tempLocalSymbol As LocalSymbol Dim tempLocal As BoundLocal Dim expressions = ArrayBuilder(Of BoundExpression).GetInstance() Dim newPlaceholder As BoundWithLValueExpressionPlaceholder If _inExpressionLambda Then ' A temp is not needed for this case tempLocalSymbol = Nothing tempLocal = Nothing ' Simply replace placeholder with a copy, it will be dropped by Expression Tree rewriter. The copy is needed to ' keep the double rewrite tracking happy. newPlaceholder = New BoundWithLValueExpressionPlaceholder(node.PlaceholderOpt.Syntax, node.PlaceholderOpt.Type) AddPlaceholderReplacement(node.PlaceholderOpt, newPlaceholder) Else ' Create a temp symbol ' Dim temp as CollectionType ' Create assignment for the rewritten object ' creation expression to the temp ' temp = new CollectionType(param1) tempLocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) tempLocal = New BoundLocal(syntaxNode, tempLocalSymbol, expressionType) Dim temporaryAssignment = New BoundAssignmentOperator(syntaxNode, tempLocal, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) expressions.Add(temporaryAssignment) newPlaceholder = Nothing AddPlaceholderReplacement(node.PlaceholderOpt, tempLocal) End If Dim initializerCount = node.Initializers.Length ' rewrite the invocation expressions and add them to the expression of the sequence ' temp.Add(...) For initializerIndex = 0 To initializerCount - 1 ' NOTE: if the method Add(...) is omitted we build a local which ' seems to be redundant, this will optimized out later ' by stack scheduler Dim initializer As BoundExpression = node.Initializers(initializerIndex) If Not IsOmittedBoundCall(initializer) Then expressions.Add(VisitExpressionNode(initializer)) End If Next RemovePlaceholderReplacement(node.PlaceholderOpt) If _inExpressionLambda Then Debug.Assert(tempLocalSymbol Is Nothing) Debug.Assert(tempLocal Is Nothing) ' NOTE: if inside expression lambda we rewrite the collection initializer ' NOTE: node and attach it back to object creation expression, it will be ' NOTE: rewritten later in ExpressionLambdaRewriter ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(newPlaceholder, expressions.ToImmutableAndFree(), node.Type)) Else Debug.Assert(tempLocalSymbol IsNot Nothing) Debug.Assert(tempLocal IsNot Nothing) Return New BoundSequence(syntaxNode, ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol), expressions.ToImmutableAndFree(), tempLocal.MakeRValue(), expressionType) End If End Function ''' <summary> ''' Rewrites a ObjectInitializerExpression to either a statement list (in case the there is no temporary used) or a bound ''' sequence expression (in case there is a temporary used). The information whether to use a temporary or not is ''' stored in the bound object member initializer node itself. ''' ''' E.g. the following code: ''' Dim x = New RefTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' Dim temp as RefTypeName ''' temp = new RefTypeName(param1) ''' temp.FieldName1 = 23 ''' temp.FieldName2 = temp.FieldName3 ''' temp.FieldName4 = x.FieldName1 ''' x = temp ''' where the last assignment is not part of this rewriting, because the BoundObjectInitializerExpression ''' only represents the object creation expression with the initialization. ''' ''' In a case where no temporary is used the following code: ''' Dim x As New ValueTypeName(param1) With {.FieldName1 = 23, .FieldName2 = .FieldName3, .FieldName4 = x.FieldName1} ''' gets rewritten to ''' x = new ValueTypeName(param1) ''' x.FieldName1 = 23 ''' x.FieldName2 = x.FieldName3 ''' x.FieldName4 = x.FieldName1 ''' </summary> ''' <param name="node">The BoundObjectInitializerExpression that should be rewritten.</param> ''' <returns>A bound sequence for the object creation expression containing the invocation expressions, or a ''' bound statement list if no temporary should be used.</returns> Public Function RewriteObjectInitializerExpression( node As BoundObjectInitializerExpression, objectCreationExpression As BoundExpression, rewrittenObjectCreationExpression As BoundExpression ) As BoundNode Dim targetObjectReference As BoundExpression Dim expressionType = node.Type Dim initializerCount = node.Initializers.Length Dim syntaxNode = node.Syntax Dim sequenceType As TypeSymbol Dim sequenceTemporaries As ImmutableArray(Of LocalSymbol) Dim sequenceValueExpression As BoundExpression Debug.Assert(node.PlaceholderOpt IsNot Nothing) ' NOTE: If we are in an expression lambda not all object initializers are allowed, essentially ' NOTE: everything requiring temp local creation is disabled; this rule is not applicable to ' NOTE: locals that are created and ONLY used on left-hand-side of initializer assignments, ' NOTE: ExpressionLambdaRewriter will get rid of them ' NOTE: In order ExpressionLambdaRewriter to be able to detect such locals being used on the ' NOTE: *right* side of initializer assignments we rewrite node.PlaceholderOpt into itself If node.CreateTemporaryLocalForInitialization Then ' create temporary ' Dim temp as RefTypeName Dim tempLocalSymbol As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, SynthesizedLocalKind.LoweringTemp) sequenceType = expressionType sequenceTemporaries = ImmutableArray.Create(Of LocalSymbol)(tempLocalSymbol) targetObjectReference = If(_inExpressionLambda, DirectCast(node.PlaceholderOpt, BoundExpression), New BoundLocal(syntaxNode, tempLocalSymbol, expressionType)) sequenceValueExpression = targetObjectReference.MakeRValue() AddPlaceholderReplacement(node.PlaceholderOpt, targetObjectReference) Else ' Get the receiver for the current initialized variable in case of an "AsNew" declaration ' this is the only case where there might be no temporary needed. ' The replacement for this placeholder was added in VisitAsNewLocalDeclarations. targetObjectReference = PlaceholderReplacement(node.PlaceholderOpt) sequenceType = GetSpecialType(SpecialType.System_Void) sequenceTemporaries = ImmutableArray(Of LocalSymbol).Empty sequenceValueExpression = Nothing End If Dim sequenceExpressions(initializerCount) As BoundExpression ' create assignment for object creation expression to temporary or variable declaration ' x = new TypeName(...) ' or ' temp = new TypeName(...) sequenceExpressions(0) = New BoundAssignmentOperator(syntaxNode, targetObjectReference, GenerateObjectCloneIfNeeded(objectCreationExpression, rewrittenObjectCreationExpression), suppressObjectClone:=True, type:=expressionType) ' rewrite the assignment expressions and add them to the statement list ' x.FieldName = value expression ' or ' temp.FieldName = value expression For initializerIndex = 0 To initializerCount - 1 If _inExpressionLambda Then ' NOTE: Inside expression lambda we rewrite only right-hand-side of the assignments, left part ' NOTE: will be kept unchanged to make sure we got proper symbol out of it Dim assignment = DirectCast(node.Initializers(initializerIndex), BoundAssignmentOperator) Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing) sequenceExpressions(initializerIndex + 1) = assignment.Update(assignment.Left, assignment.LeftOnTheRightOpt, VisitExpressionNode(assignment.Right), True, assignment.Type) Else sequenceExpressions(initializerIndex + 1) = VisitExpressionNode(node.Initializers(initializerIndex)) End If Next If node.CreateTemporaryLocalForInitialization Then RemovePlaceholderReplacement(node.PlaceholderOpt) End If If _inExpressionLambda Then ' when converting object initializer inside expression lambdas we want to keep ' object initializer in object creation expression; we just store visited initializers ' back to the original object initializer and update the original object creation expression ' create new initializers Dim newInitializers(initializerCount - 1) As BoundExpression Dim errors As Boolean = False For index = 0 To initializerCount - 1 newInitializers(index) = sequenceExpressions(index + 1) Next ' Rewrite object creation Return ReplaceObjectOrCollectionInitializer( rewrittenObjectCreationExpression, node.Update(node.CreateTemporaryLocalForInitialization, node.PlaceholderOpt, newInitializers.AsImmutableOrNull(), node.Type)) End If Return New BoundSequence(syntaxNode, sequenceTemporaries, sequenceExpressions.AsImmutableOrNull, sequenceValueExpression, sequenceType) End Function Private Function ReplaceObjectOrCollectionInitializer(rewrittenObjectCreationExpression As BoundExpression, rewrittenInitializer As BoundObjectInitializerExpressionBase) As BoundExpression Select Case rewrittenObjectCreationExpression.Kind Case BoundKind.ObjectCreationExpression Dim objCreation = DirectCast(rewrittenObjectCreationExpression, BoundObjectCreationExpression) Return objCreation.Update(objCreation.ConstructorOpt, objCreation.Arguments, objCreation.DefaultArguments, rewrittenInitializer, objCreation.Type) Case BoundKind.NewT Dim newT = DirectCast(rewrittenObjectCreationExpression, BoundNewT) Return newT.Update(rewrittenInitializer, newT.Type) Case BoundKind.Sequence ' NOTE: is rewrittenObjectCreationExpression is not an object creation expression, it ' NOTE: was probably wrapped with sequence which means that this case is not supported ' NOTE: inside expression lambdas. Dim sequence = DirectCast(rewrittenObjectCreationExpression, BoundSequence) Debug.Assert(sequence.ValueOpt IsNot Nothing AndAlso sequence.ValueOpt.Kind = BoundKind.ObjectCreationExpression) Return sequence.Update(sequence.Locals, sequence.SideEffects, ReplaceObjectOrCollectionInitializer(sequence.ValueOpt, rewrittenInitializer), sequence.Type) Case Else Throw ExceptionUtilities.UnexpectedValue(rewrittenObjectCreationExpression.Kind) End Select End Function End Class End Namespace
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertyAccessorSymbol.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.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourcePropertyAccessorSymbol Inherits SourceMethodSymbol Protected ReadOnly m_property As SourcePropertySymbol Private ReadOnly _name As String Private _lazyMetadataName As String Private _lazyExplicitImplementations As ImmutableArray(Of MethodSymbol) ' lazily populated with explicit implementations ' Parameters. Private _lazyParameters As ImmutableArray(Of ParameterSymbol) ' Return type. Void for a Sub. Private _lazyReturnType As TypeSymbol Friend Sub New(propertySymbol As SourcePropertySymbol, name As String, flags As SourceMemberFlags, syntaxRef As SyntaxReference, locations As ImmutableArray(Of Location)) MyBase.New( propertySymbol.ContainingSourceType, If(flags.ToMethodKind() = MethodKind.PropertyGet, flags, flags And Not SourceMemberFlags.Iterator), syntaxRef, locations) m_property = propertySymbol _name = name End Sub Private Shared Function SynthesizeAutoGetterParameters(getter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol) If propertySymbol.ParameterCount = 0 Then Return ImmutableArray(Of ParameterSymbol).Empty End If Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount) propertySymbol.CloneParametersForAccessor(getter, parameters) Return parameters.ToImmutableAndFree() End Function Private Shared Function SynthesizeAutoSetterParameters(setter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol) Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter( setter, propertySymbol, If(propertySymbol.IsAutoProperty, StringConstants.AutoPropertyValueParameterName, StringConstants.ValueParameterName)) If propertySymbol.ParameterCount = 0 Then Return ImmutableArray.Create(valueParameter) End If Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount + 1) propertySymbol.CloneParametersForAccessor(setter, parameters) parameters.Add(valueParameter) Return parameters.ToImmutableAndFree() End Function Friend Shared Function CreatePropertyAccessor(propertySymbol As SourcePropertySymbol, kindFlags As SourceMemberFlags, propertyFlags As SourceMemberFlags, binder As Binder, blockSyntax As AccessorBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol Dim syntax = blockSyntax.BlockStatement Dim modifiers = binder.DecodeModifiers(syntax.Modifiers, SourceMemberFlags.AllAccessibilityModifiers, ERRID.ERR_BadPropertyAccessorFlags, Accessibility.NotApplicable, diagnostics) If (modifiers.FoundFlags And SourceMemberFlags.Private) <> 0 Then ' Private accessors cannot be overridable. propertyFlags = propertyFlags And (Not SourceMemberFlags.Overridable) End If If (modifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then Select Case propertySymbol.ContainingType.TypeKind Case TypeKind.Structure binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_StructCantUseVarSpecifier1, diagnostics, SyntaxKind.ProtectedKeyword) modifiers = New MemberModifiers(modifiers.FoundFlags And Not SourceMemberFlags.Protected, modifiers.ComputedFlags And Not SourceMemberFlags.AccessibilityMask) Case TypeKind.Module Debug.Assert((SourceMemberFlags.Protected And SourceMemberFlags.InvalidInModule) <> 0) binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadFlagsOnStdModuleProperty1, diagnostics, SyntaxKind.ProtectedKeyword) End Select End If ' Include modifiers from the containing property. Dim flags = modifiers.AllFlags Or kindFlags Or propertyFlags Dim methodKind = kindFlags.ToMethodKind() If methodKind = MethodKind.PropertySet Then flags = flags Or SourceMemberFlags.MethodIsSub End If Dim method As New SourcePropertyAccessorSymbol( propertySymbol, Binder.GetAccessorName(propertySymbol.Name, methodKind, propertySymbol.IsCompilationOutputWinMdObj()), flags, binder.GetSyntaxReference(syntax), ImmutableArray.Create(syntax.DeclarationKeyword.GetLocation())) Return method End Function Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return m_property.GetAccessorOverride(getter:=(MethodKind = MethodKind.PropertyGet)) End Get End Property Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) Get Return OverriddenMembersResult(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Not Me.m_property.IsCustomProperty OrElse MyBase.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return If(Me.m_property.IsCustomProperty, MyBase.DeclaringSyntaxReferences, ImmutableArray(Of SyntaxReference).Empty) End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then ' VB compiler uses different rules for accessors that other members or the associated properties ' (probably a bug, but we have to maintain binary compatibility now). An accessor name is set to match ' its overridden method, regardless of what happens to its associated property. Dim overriddenMethod = Me.OverriddenMethod If overriddenMethod IsNot Nothing Then Interlocked.CompareExchange(_lazyMetadataName, overriddenMethod.MetadataName, Nothing) Else Interlocked.CompareExchange(_lazyMetadataName, _name, Nothing) End If End If Return _lazyMetadataName End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Dim accessibility = Me.LocalAccessibility If accessibility <> Accessibility.NotApplicable Then Return accessibility End If Dim propertyAccessibility = m_property.DeclaredAccessibility Debug.Assert(propertyAccessibility <> Accessibility.NotApplicable) Return propertyAccessibility End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Dim retType = _lazyReturnType If retType Is Nothing Then Dim diagBag = BindingDiagnosticBag.GetInstance() Dim sourceModule = ContainingSourceModule Dim errorLocation As SyntaxNodeOrToken = Nothing retType = GetReturnType(sourceModule, errorLocation, diagBag) If Not errorLocation.IsKind(SyntaxKind.None) Then Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance() Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing retType.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) If useSiteDiagnosticsBuilder IsNot Nothing Then diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder) End If For Each diag In diagnosticsBuilder diagBag.Add(diag.UseSiteInfo, errorLocation.GetLocation()) Next diagnosticsBuilder.Free() End If sourceModule.AtomicStoreReferenceAndDiagnostics( _lazyReturnType, retType, diagBag) diagBag.Free() retType = _lazyReturnType End If Return retType End Get End Property Private Function GetReturnType(sourceModule As SourceModuleSymbol, ByRef errorLocation As SyntaxNodeOrToken, diagBag As BindingDiagnosticBag) As TypeSymbol Select Case MethodKind Case MethodKind.PropertyGet Dim accessorSym = DirectCast(Me, SourcePropertyAccessorSymbol) Dim prop = DirectCast(accessorSym.AssociatedSymbol, PropertySymbol) Dim result = prop.Type Dim overriddenMethod = Me.OverriddenMethod If overriddenMethod IsNot Nothing AndAlso overriddenMethod.ReturnType.IsSameTypeIgnoringAll(result) Then result = overriddenMethod.ReturnType End If Return result Case MethodKind.PropertySet Debug.Assert(Me.IsSub) Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType) Return binder.GetSpecialType(SpecialType.System_Void, Me.DeclarationSyntax, diagBag) Case Else Throw ExceptionUtilities.Unreachable() End Select End Function Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Dim params = _lazyParameters If params.IsDefault Then Dim diagBag = BindingDiagnosticBag.GetInstance() Dim sourceModule = ContainingSourceModule params = GetParameters(sourceModule, diagBag) For Each param In params ' TODO: The check for Locations is to rule out cases such as implicit parameters ' from property accessors but it allows explicit accessor parameters. Is that correct? If param.Locations.Length > 0 Then ' Note: Errors are reported on the parameter name. Ideally, we should ' match Dev10 and report errors on the parameter type syntax instead. param.Type.CheckAllConstraints(param.Locations(0), diagBag, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) End If Next sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagBag) diagBag.Free() params = _lazyParameters End If Return params End Get End Property Private Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) If m_property.IsCustomProperty Then Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType) binder = New LocationSpecificBinder(BindingLocation.PropertyAccessorSignature, Me, binder) Return BindParameters(Me.m_property, Me, Me.Locations.FirstOrDefault, binder, BlockSyntax.BlockStatement.ParameterList, diagBag) Else ' synthesize parameters for auto-properties and abstract properties Return If(MethodKind = MethodKind.PropertyGet, SynthesizeAutoGetterParameters(Me, m_property), SynthesizeAutoSetterParameters(Me, m_property)) End If End Function Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return m_property End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return m_property.ShadowsExplicitly End Get End Property ' Friend Overrides Function GetLexicalSortKey() As LexicalSortKey Return If(m_property.IsCustomProperty, MyBase.GetLexicalSortKey(), m_property.GetLexicalSortKey()) End Function Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get If _lazyExplicitImplementations.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange( _lazyExplicitImplementations, m_property.GetAccessorImplementations(getter:=(MethodKind = MethodKind.PropertyGet)), Nothing) End If Return _lazyExplicitImplementations End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overriddenMethod = Me.OverriddenMethod If overriddenMethod IsNot Nothing Then Return overriddenMethod.ReturnTypeCustomModifiers End If Return If(Me.MethodKind = MethodKind.PropertySet, ImmutableArray(Of CustomModifier).Empty, m_property.TypeCustomModifiers) End Get End Property Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If m_property.IsCustomProperty Then Return OneOrMany.Create(AttributeDeclarationSyntaxList) Else Return Nothing End If End Function Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' getter return type attributes should be copied from the property return type attributes Debug.Assert(Me.MethodKind = MethodKind.PropertySet) Return Nothing End Function Protected Overrides ReadOnly Property BoundReturnTypeAttributesSource As SourcePropertySymbol Get Return If(Me.MethodKind = MethodKind.PropertyGet, m_property, Nothing) End Get End Property Friend ReadOnly Property LocalAccessibility As Accessibility Get Return MyBase.DeclaredAccessibility End Get End Property ''' <summary> ''' Bind parameters declared on the accessor and combine with any ''' parameters declared on the property. If there are no explicit parameters ''' and this is a setter, create a synthesized value parameter. ''' </summary> Private Shared Function BindParameters(propertySymbol As SourcePropertySymbol, method As SourcePropertyAccessorSymbol, location As Location, binder As Binder, parameterListOpt As ParameterListSyntax, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) Dim propertyParameters = propertySymbol.Parameters Dim nPropertyParameters = propertyParameters.Length Dim isSetter As Boolean = (method.MethodKind = MethodKind.PropertySet) Dim parameterListSyntax = If(parameterListOpt Is Nothing OrElse Not isSetter, Nothing, parameterListOpt.Parameters) Dim synthesizeParameter = isSetter AndAlso (parameterListSyntax.Count = 0) Dim nParameters = nPropertyParameters + parameterListSyntax.Count + If(synthesizeParameter, 1, 0) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(nParameters) propertySymbol.CloneParametersForAccessor(method, parameters) If parameterListSyntax.Count > 0 Then ' Explicit accessor parameters. Bind all parameters (even though at most one ' parameter was expected), to ensure all diagnostics are generated and ' ensure parameter symbols are available for binding the method body. binder.DecodeParameterList( method, False, SourceMemberFlags.None, parameterListSyntax, parameters, s_checkParameterModifierCallback, diagnostics) ' Check for duplicate parameter names across accessor (setter) and property. ' It is only necessary to check the one expected setter parameter since we'll report ' setter must have one parameter otherwise, and it's not necessary to check for ' duplicates if the setter parameter is named 'Value' since we'll report property ' cannot contain parameter named 'Value' if there is a duplicate in that case. Dim param = parameters(nPropertyParameters) If Not IdentifierComparison.Equals(param.Name, StringConstants.ValueParameterName) Then Dim paramSyntax = parameterListSyntax(0) Binder.CheckParameterNameNotDuplicate(parameters, nPropertyParameters, paramSyntax, param, diagnostics) End If If parameterListSyntax.Count = 1 Then ' Verify parameter type matches property type. Dim propertyType = propertySymbol.Type Dim valueParameter = parameters(parameters.Count - 1) Dim valueParameterType = valueParameter.Type If Not propertyType.IsSameTypeIgnoringAll(valueParameterType) Then If (Not propertyType.IsErrorType()) AndAlso (Not valueParameterType.IsErrorType()) Then diagnostics.Add(ERRID.ERR_SetValueNotPropertyType, valueParameter.Locations(0)) End If Else Dim overriddenMethod = method.OverriddenMethod If overriddenMethod IsNot Nothing Then Dim overriddenParameter = overriddenMethod.Parameters(parameters.Count - 1) If overriddenParameter.Type.IsSameTypeIgnoringAll(valueParameterType) AndAlso CustomModifierUtils.CopyParameterCustomModifiers(overriddenParameter, valueParameter) Then parameters(parameters.Count - 1) = valueParameter End If End If End If Else diagnostics.Add(ERRID.ERR_SetHasOnlyOneParam, location) End If ElseIf synthesizeParameter Then ' No explicit set accessor parameter. Create a synthesized parameter. Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter(method, propertySymbol, parameterName:=StringConstants.ValueParameterName) parameters.Add(valueParameter) End If Return parameters.ToImmutableAndFree() End Function Private Shared ReadOnly s_checkParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckParameterModifier Private Shared Function CheckParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags If flag <> SourceParameterFlags.ByVal Then Dim location = token.GetLocation() diagnostics.Add(ERRID.ERR_SetHasToBeByVal1, location, token.ToString()) Return flag And SourceParameterFlags.ByVal End If Return SourceParameterFlags.ByVal End Function Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock Debug.Assert(Not m_property.IsMustOverride) If m_property.IsAutoProperty Then Return SynthesizedPropertyAccessorHelper.GetBoundMethodBody(Me, m_property.AssociatedField, methodBodyBinder) Else Return MyBase.GetBoundMethodBody(compilationState, diagnostics, methodBodyBinder) End If End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) If arguments.SymbolPart = AttributeLocation.None Then If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().IsPropertyAccessorWithDebuggerHiddenAttribute = True End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend ReadOnly Property HasDebuggerHiddenAttribute As Boolean Get Dim attributeData = GetDecodedWellKnownAttributeData() Return attributeData IsNot Nothing AndAlso attributeData.IsPropertyAccessorWithDebuggerHiddenAttribute End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If m_property.IsAutoProperty Then Dim compilation = DeclaringCompilation AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) ' 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 If End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return Not m_property.IsAutoProperty AndAlso MyBase.GenerateDebugInfoImpl 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 System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourcePropertyAccessorSymbol Inherits SourceMethodSymbol Protected ReadOnly m_property As SourcePropertySymbol Private ReadOnly _name As String Private _lazyMetadataName As String Private _lazyExplicitImplementations As ImmutableArray(Of MethodSymbol) ' lazily populated with explicit implementations ' Parameters. Private _lazyParameters As ImmutableArray(Of ParameterSymbol) ' Return type. Void for a Sub. Private _lazyReturnType As TypeSymbol Friend Sub New(propertySymbol As SourcePropertySymbol, name As String, flags As SourceMemberFlags, syntaxRef As SyntaxReference, locations As ImmutableArray(Of Location)) MyBase.New( propertySymbol.ContainingSourceType, If(flags.ToMethodKind() = MethodKind.PropertyGet, flags, flags And Not SourceMemberFlags.Iterator), syntaxRef, locations) m_property = propertySymbol _name = name End Sub Private Shared Function SynthesizeAutoGetterParameters(getter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol) If propertySymbol.ParameterCount = 0 Then Return ImmutableArray(Of ParameterSymbol).Empty End If Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount) propertySymbol.CloneParametersForAccessor(getter, parameters) Return parameters.ToImmutableAndFree() End Function Private Shared Function SynthesizeAutoSetterParameters(setter As SourcePropertyAccessorSymbol, propertySymbol As SourcePropertySymbol) As ImmutableArray(Of ParameterSymbol) Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter( setter, propertySymbol, If(propertySymbol.IsAutoProperty, StringConstants.AutoPropertyValueParameterName, StringConstants.ValueParameterName)) If propertySymbol.ParameterCount = 0 Then Return ImmutableArray.Create(valueParameter) End If Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(propertySymbol.ParameterCount + 1) propertySymbol.CloneParametersForAccessor(setter, parameters) parameters.Add(valueParameter) Return parameters.ToImmutableAndFree() End Function Friend Shared Function CreatePropertyAccessor(propertySymbol As SourcePropertySymbol, kindFlags As SourceMemberFlags, propertyFlags As SourceMemberFlags, binder As Binder, blockSyntax As AccessorBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol Dim syntax = blockSyntax.BlockStatement Dim modifiers = binder.DecodeModifiers(syntax.Modifiers, SourceMemberFlags.AllAccessibilityModifiers, ERRID.ERR_BadPropertyAccessorFlags, Accessibility.NotApplicable, diagnostics) If (modifiers.FoundFlags And SourceMemberFlags.Private) <> 0 Then ' Private accessors cannot be overridable. propertyFlags = propertyFlags And (Not SourceMemberFlags.Overridable) End If If (modifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then Select Case propertySymbol.ContainingType.TypeKind Case TypeKind.Structure binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_StructCantUseVarSpecifier1, diagnostics, SyntaxKind.ProtectedKeyword) modifiers = New MemberModifiers(modifiers.FoundFlags And Not SourceMemberFlags.Protected, modifiers.ComputedFlags And Not SourceMemberFlags.AccessibilityMask) Case TypeKind.Module Debug.Assert((SourceMemberFlags.Protected And SourceMemberFlags.InvalidInModule) <> 0) binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadFlagsOnStdModuleProperty1, diagnostics, SyntaxKind.ProtectedKeyword) End Select End If ' Include modifiers from the containing property. Dim flags = modifiers.AllFlags Or kindFlags Or propertyFlags Dim methodKind = kindFlags.ToMethodKind() If methodKind = MethodKind.PropertySet Then flags = flags Or SourceMemberFlags.MethodIsSub End If Dim method As New SourcePropertyAccessorSymbol( propertySymbol, Binder.GetAccessorName(propertySymbol.Name, methodKind, propertySymbol.IsCompilationOutputWinMdObj()), flags, binder.GetSyntaxReference(syntax), ImmutableArray.Create(syntax.DeclarationKeyword.GetLocation())) Return method End Function Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol Get Return m_property.GetAccessorOverride(getter:=(MethodKind = MethodKind.PropertyGet)) End Get End Property Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) Get Return OverriddenMembersResult(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Not Me.m_property.IsCustomProperty OrElse MyBase.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return If(Me.m_property.IsCustomProperty, MyBase.DeclaringSyntaxReferences, ImmutableArray(Of SyntaxReference).Empty) End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then ' VB compiler uses different rules for accessors that other members or the associated properties ' (probably a bug, but we have to maintain binary compatibility now). An accessor name is set to match ' its overridden method, regardless of what happens to its associated property. Dim overriddenMethod = Me.OverriddenMethod If overriddenMethod IsNot Nothing Then Interlocked.CompareExchange(_lazyMetadataName, overriddenMethod.MetadataName, Nothing) Else Interlocked.CompareExchange(_lazyMetadataName, _name, Nothing) End If End If Return _lazyMetadataName End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Dim accessibility = Me.LocalAccessibility If accessibility <> Accessibility.NotApplicable Then Return accessibility End If Dim propertyAccessibility = m_property.DeclaredAccessibility Debug.Assert(propertyAccessibility <> Accessibility.NotApplicable) Return propertyAccessibility End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Dim retType = _lazyReturnType If retType Is Nothing Then Dim diagBag = BindingDiagnosticBag.GetInstance() Dim sourceModule = ContainingSourceModule Dim errorLocation As SyntaxNodeOrToken = Nothing retType = GetReturnType(sourceModule, errorLocation, diagBag) If Not errorLocation.IsKind(SyntaxKind.None) Then Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance() Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing retType.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) If useSiteDiagnosticsBuilder IsNot Nothing Then diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder) End If For Each diag In diagnosticsBuilder diagBag.Add(diag.UseSiteInfo, errorLocation.GetLocation()) Next diagnosticsBuilder.Free() End If sourceModule.AtomicStoreReferenceAndDiagnostics( _lazyReturnType, retType, diagBag) diagBag.Free() retType = _lazyReturnType End If Return retType End Get End Property Private Function GetReturnType(sourceModule As SourceModuleSymbol, ByRef errorLocation As SyntaxNodeOrToken, diagBag As BindingDiagnosticBag) As TypeSymbol Select Case MethodKind Case MethodKind.PropertyGet Dim accessorSym = DirectCast(Me, SourcePropertyAccessorSymbol) Dim prop = DirectCast(accessorSym.AssociatedSymbol, PropertySymbol) Dim result = prop.Type Dim overriddenMethod = Me.OverriddenMethod If overriddenMethod IsNot Nothing AndAlso overriddenMethod.ReturnType.IsSameTypeIgnoringAll(result) Then result = overriddenMethod.ReturnType End If Return result Case MethodKind.PropertySet Debug.Assert(Me.IsSub) Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType) Return binder.GetSpecialType(SpecialType.System_Void, Me.DeclarationSyntax, diagBag) Case Else Throw ExceptionUtilities.Unreachable() End Select End Function Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Dim params = _lazyParameters If params.IsDefault Then Dim diagBag = BindingDiagnosticBag.GetInstance() Dim sourceModule = ContainingSourceModule params = GetParameters(sourceModule, diagBag) For Each param In params ' TODO: The check for Locations is to rule out cases such as implicit parameters ' from property accessors but it allows explicit accessor parameters. Is that correct? If param.Locations.Length > 0 Then ' Note: Errors are reported on the parameter name. Ideally, we should ' match Dev10 and report errors on the parameter type syntax instead. param.Type.CheckAllConstraints(param.Locations(0), diagBag, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) End If Next sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagBag) diagBag.Free() params = _lazyParameters End If Return params End Get End Property Private Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) If m_property.IsCustomProperty Then Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, Me.m_property.ContainingSourceType) binder = New LocationSpecificBinder(BindingLocation.PropertyAccessorSignature, Me, binder) Return BindParameters(Me.m_property, Me, Me.Locations.FirstOrDefault, binder, BlockSyntax.BlockStatement.ParameterList, diagBag) Else ' synthesize parameters for auto-properties and abstract properties Return If(MethodKind = MethodKind.PropertyGet, SynthesizeAutoGetterParameters(Me, m_property), SynthesizeAutoSetterParameters(Me, m_property)) End If End Function Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return m_property End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return m_property.ShadowsExplicitly End Get End Property ' Friend Overrides Function GetLexicalSortKey() As LexicalSortKey Return If(m_property.IsCustomProperty, MyBase.GetLexicalSortKey(), m_property.GetLexicalSortKey()) End Function Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get If _lazyExplicitImplementations.IsDefault Then ImmutableInterlocked.InterlockedCompareExchange( _lazyExplicitImplementations, m_property.GetAccessorImplementations(getter:=(MethodKind = MethodKind.PropertyGet)), Nothing) End If Return _lazyExplicitImplementations End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overriddenMethod = Me.OverriddenMethod If overriddenMethod IsNot Nothing Then Return overriddenMethod.ReturnTypeCustomModifiers End If Return If(Me.MethodKind = MethodKind.PropertySet, ImmutableArray(Of CustomModifier).Empty, m_property.TypeCustomModifiers) End Get End Property Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If m_property.IsCustomProperty Then Return OneOrMany.Create(AttributeDeclarationSyntaxList) Else Return Nothing End If End Function Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' getter return type attributes should be copied from the property return type attributes Debug.Assert(Me.MethodKind = MethodKind.PropertySet) Return Nothing End Function Protected Overrides ReadOnly Property BoundReturnTypeAttributesSource As SourcePropertySymbol Get Return If(Me.MethodKind = MethodKind.PropertyGet, m_property, Nothing) End Get End Property Friend ReadOnly Property LocalAccessibility As Accessibility Get Return MyBase.DeclaredAccessibility End Get End Property ''' <summary> ''' Bind parameters declared on the accessor and combine with any ''' parameters declared on the property. If there are no explicit parameters ''' and this is a setter, create a synthesized value parameter. ''' </summary> Private Shared Function BindParameters(propertySymbol As SourcePropertySymbol, method As SourcePropertyAccessorSymbol, location As Location, binder As Binder, parameterListOpt As ParameterListSyntax, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) Dim propertyParameters = propertySymbol.Parameters Dim nPropertyParameters = propertyParameters.Length Dim isSetter As Boolean = (method.MethodKind = MethodKind.PropertySet) Dim parameterListSyntax = If(parameterListOpt Is Nothing OrElse Not isSetter, Nothing, parameterListOpt.Parameters) Dim synthesizeParameter = isSetter AndAlso (parameterListSyntax.Count = 0) Dim nParameters = nPropertyParameters + parameterListSyntax.Count + If(synthesizeParameter, 1, 0) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(nParameters) propertySymbol.CloneParametersForAccessor(method, parameters) If parameterListSyntax.Count > 0 Then ' Explicit accessor parameters. Bind all parameters (even though at most one ' parameter was expected), to ensure all diagnostics are generated and ' ensure parameter symbols are available for binding the method body. binder.DecodeParameterList( method, False, SourceMemberFlags.None, parameterListSyntax, parameters, s_checkParameterModifierCallback, diagnostics) ' Check for duplicate parameter names across accessor (setter) and property. ' It is only necessary to check the one expected setter parameter since we'll report ' setter must have one parameter otherwise, and it's not necessary to check for ' duplicates if the setter parameter is named 'Value' since we'll report property ' cannot contain parameter named 'Value' if there is a duplicate in that case. Dim param = parameters(nPropertyParameters) If Not IdentifierComparison.Equals(param.Name, StringConstants.ValueParameterName) Then Dim paramSyntax = parameterListSyntax(0) Binder.CheckParameterNameNotDuplicate(parameters, nPropertyParameters, paramSyntax, param, diagnostics) End If If parameterListSyntax.Count = 1 Then ' Verify parameter type matches property type. Dim propertyType = propertySymbol.Type Dim valueParameter = parameters(parameters.Count - 1) Dim valueParameterType = valueParameter.Type If Not propertyType.IsSameTypeIgnoringAll(valueParameterType) Then If (Not propertyType.IsErrorType()) AndAlso (Not valueParameterType.IsErrorType()) Then diagnostics.Add(ERRID.ERR_SetValueNotPropertyType, valueParameter.Locations(0)) End If Else Dim overriddenMethod = method.OverriddenMethod If overriddenMethod IsNot Nothing Then Dim overriddenParameter = overriddenMethod.Parameters(parameters.Count - 1) If overriddenParameter.Type.IsSameTypeIgnoringAll(valueParameterType) AndAlso CustomModifierUtils.CopyParameterCustomModifiers(overriddenParameter, valueParameter) Then parameters(parameters.Count - 1) = valueParameter End If End If End If Else diagnostics.Add(ERRID.ERR_SetHasOnlyOneParam, location) End If ElseIf synthesizeParameter Then ' No explicit set accessor parameter. Create a synthesized parameter. Dim valueParameter = SynthesizedParameterSymbol.CreateSetAccessorValueParameter(method, propertySymbol, parameterName:=StringConstants.ValueParameterName) parameters.Add(valueParameter) End If Return parameters.ToImmutableAndFree() End Function Private Shared ReadOnly s_checkParameterModifierCallback As Binder.CheckParameterModifierDelegate = AddressOf CheckParameterModifier Private Shared Function CheckParameterModifier(container As Symbol, token As SyntaxToken, flag As SourceParameterFlags, diagnostics As BindingDiagnosticBag) As SourceParameterFlags If flag <> SourceParameterFlags.ByVal Then Dim location = token.GetLocation() diagnostics.Add(ERRID.ERR_SetHasToBeByVal1, location, token.ToString()) Return flag And SourceParameterFlags.ByVal End If Return SourceParameterFlags.ByVal End Function Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock Debug.Assert(Not m_property.IsMustOverride) If m_property.IsAutoProperty Then Return SynthesizedPropertyAccessorHelper.GetBoundMethodBody(Me, m_property.AssociatedField, methodBodyBinder) Else Return MyBase.GetBoundMethodBody(compilationState, diagnostics, methodBodyBinder) End If End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) If arguments.SymbolPart = AttributeLocation.None Then If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().IsPropertyAccessorWithDebuggerHiddenAttribute = True End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend ReadOnly Property HasDebuggerHiddenAttribute As Boolean Get Dim attributeData = GetDecodedWellKnownAttributeData() Return attributeData IsNot Nothing AndAlso attributeData.IsPropertyAccessorWithDebuggerHiddenAttribute End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If m_property.IsAutoProperty Then Dim compilation = DeclaringCompilation AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) ' 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 If End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return Not m_property.IsAutoProperty AndAlso MyBase.GenerateDebugInfoImpl End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpF1Help.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpF1Help : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpF1Help(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpF1Help)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)] private void F1Help() { var text = @" using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace F1TestNamespace { #region TaoRegion abstract class ShapesClass { } class Program$$ { public static void Main() { } public IEnumerable<int> Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i = numbers.First(); int j = Array.IndexOf(numbers, 1); var lowNums1 = from n in numbers orderby n ascending where n < 5 select n; var numberGroups = from n in numbers let m = 1 join p in numbers on i equals p group n by n % 5 into g select new { Remainder = g.Key, Numbers = g }; foreach (int element in numbers) yield return i; } } #endregion TaoRegion }"; SetUpEditor(text); Verify("abstract", "abstract_CSharpKeyword"); Verify("ascending", "ascending_CSharpKeyword"); Verify("from", "from_CSharpKeyword"); Verify("First();", "System.Linq.Enumerable.First``1"); } private void Verify(string word, string expectedKeyword) { VisualStudio.Editor.PlaceCaret(word, charsOffset: -1); Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpF1Help : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpF1Help(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpF1Help)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)] private void F1Help() { var text = @" using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace F1TestNamespace { #region TaoRegion abstract class ShapesClass { } class Program$$ { public static void Main() { } public IEnumerable<int> Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int i = numbers.First(); int j = Array.IndexOf(numbers, 1); var lowNums1 = from n in numbers orderby n ascending where n < 5 select n; var numberGroups = from n in numbers let m = 1 join p in numbers on i equals p group n by n % 5 into g select new { Remainder = g.Key, Numbers = g }; foreach (int element in numbers) yield return i; } } #endregion TaoRegion }"; SetUpEditor(text); Verify("abstract", "abstract_CSharpKeyword"); Verify("ascending", "ascending_CSharpKeyword"); Verify("from", "from_CSharpKeyword"); Verify("First();", "System.Linq.Enumerable.First``1"); } private void Verify(string word, string expectedKeyword) { VisualStudio.Editor.PlaceCaret(word, charsOffset: -1); Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword()); } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/CSharp/Portable/Formatting/CSharpAccessibilityModifiersNewDocumentFormattingProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Formatting { [ExportNewDocumentFormattingProvider(LanguageNames.CSharp), Shared] internal class CSharpAccessibilityModifiersNewDocumentFormattingProvider : INewDocumentFormattingProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAccessibilityModifiersNewDocumentFormattingProvider() { } public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language); if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never) { return document; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node)); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var service = document.GetRequiredLanguageService<IAddAccessibilityModifiersService>(); foreach (var declaration in typeDeclarations) { if (!service.ShouldUpdateAccessibilityModifier(CSharpAccessibilityFacts.Instance, declaration, accessibilityPreferences.Value, out _)) continue; // Since we format each document as they are added to a project we can't assume we know about all // of the files that are coming, so we have to opt out of changing partial classes. This especially // manifests when creating new projects as we format before we have a project at all, so we could get a // situation like this: // // File1.cs: // partial class C { } // File2.cs: // public partial class C { } // // When we see File1, we don't know about File2, so would add an internal modifier, which would result in a compile // error. var modifiers = syntaxFacts.GetModifiers(declaration); CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifiers, out _, out var declarationModifiers, out _); if (declarationModifiers.IsPartial) continue; var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken); if (type == null) continue; AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Formatting { [ExportNewDocumentFormattingProvider(LanguageNames.CSharp), Shared] internal class CSharpAccessibilityModifiersNewDocumentFormattingProvider : INewDocumentFormattingProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAccessibilityModifiersNewDocumentFormattingProvider() { } public async Task<Document> FormatNewDocumentAsync(Document document, Document? hintDocument, CancellationToken cancellationToken) { var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var accessibilityPreferences = documentOptions.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers, document.Project.Language); if (accessibilityPreferences.Value == AccessibilityModifiersRequired.Never) { return document; } var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeDeclarations = root.DescendantNodes().Where(node => syntaxFacts.IsTypeDeclaration(node)); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var service = document.GetRequiredLanguageService<IAddAccessibilityModifiersService>(); foreach (var declaration in typeDeclarations) { if (!service.ShouldUpdateAccessibilityModifier(CSharpAccessibilityFacts.Instance, declaration, accessibilityPreferences.Value, out _)) continue; // Since we format each document as they are added to a project we can't assume we know about all // of the files that are coming, so we have to opt out of changing partial classes. This especially // manifests when creating new projects as we format before we have a project at all, so we could get a // situation like this: // // File1.cs: // partial class C { } // File2.cs: // public partial class C { } // // When we see File1, we don't know about File2, so would add an internal modifier, which would result in a compile // error. var modifiers = syntaxFacts.GetModifiers(declaration); CSharpAccessibilityFacts.GetAccessibilityAndModifiers(modifiers, out _, out var declarationModifiers, out _); if (declarationModifiers.IsPartial) continue; var type = semanticModel.GetDeclaredSymbol(declaration, cancellationToken); if (type == null) continue; AddAccessibilityModifiersHelpers.UpdateDeclaration(editor, type, declaration); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CastExpressionSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class CastExpressionSyntaxExtensions { public static ExpressionSyntax Uncast(this CastExpressionSyntax node) { var leadingTrivia = node.OpenParenToken.LeadingTrivia .Concat(node.OpenParenToken.TrailingTrivia) .Concat(node.Type.GetLeadingTrivia()) .Concat(node.Type.GetTrailingTrivia()) .Concat(node.CloseParenToken.LeadingTrivia) .Concat(node.CloseParenToken.TrailingTrivia) .Concat(node.Expression.GetLeadingTrivia()) .Where(t => !t.IsElastic()); var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic()); var resultNode = node.Expression .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithAdditionalAnnotations(Simplifier.Annotation); resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); return resultNode; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class CastExpressionSyntaxExtensions { public static ExpressionSyntax Uncast(this CastExpressionSyntax node) { var leadingTrivia = node.OpenParenToken.LeadingTrivia .Concat(node.OpenParenToken.TrailingTrivia) .Concat(node.Type.GetLeadingTrivia()) .Concat(node.Type.GetTrailingTrivia()) .Concat(node.CloseParenToken.LeadingTrivia) .Concat(node.CloseParenToken.TrailingTrivia) .Concat(node.Expression.GetLeadingTrivia()) .Where(t => !t.IsElastic()); var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic()); var resultNode = node.Expression .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithAdditionalAnnotations(Simplifier.Annotation); resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); return resultNode; } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/Core/Portable/GenerateDefaultConstructors/AbstractGenerateDefaultConstructorsService.CodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { internal abstract partial class AbstractGenerateDefaultConstructorsService<TService> { private class GenerateDefaultConstructorCodeAction : AbstractCodeAction { public GenerateDefaultConstructorCodeAction( Document document, State state, IMethodSymbol constructor) : base(document, state, new[] { constructor }, GetDisplayText(state, constructor)) { } private static string GetDisplayText(State state, IMethodSymbol constructor) { var parameters = constructor.Parameters.Select(p => p.Name); var parameterString = string.Join(", ", parameters); Contract.ThrowIfNull(state.ClassType); return string.Format(FeaturesResources.Generate_constructor_0_1, state.ClassType.Name, parameterString); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { internal abstract partial class AbstractGenerateDefaultConstructorsService<TService> { private class GenerateDefaultConstructorCodeAction : AbstractCodeAction { public GenerateDefaultConstructorCodeAction( Document document, State state, IMethodSymbol constructor) : base(document, state, new[] { constructor }, GetDisplayText(state, constructor)) { } private static string GetDisplayText(State state, IMethodSymbol constructor) { var parameters = constructor.Parameters.Select(p => p.Name); var parameterString = string.Join(", ", parameters); Contract.ThrowIfNull(state.ClassType); return string.Format(FeaturesResources.Generate_constructor_0_1, state.ClassType.Name, parameterString); } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayLocalOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how locals are displayed in the description of a symbol. /// </summary> [Flags] public enum SymbolDisplayLocalOptions { /// <summary> /// Shows only the name of the local. /// For example, "x". /// </summary> None = 0, /// <summary> /// Shows the type of the local in addition to its name. /// For example, "int x" in C# or "x As Integer" in Visual Basic. /// </summary> IncludeType = 1 << 0, /// <summary> /// Shows the constant value of the local, if there is one, in addition to its name. /// For example "x = 1". /// </summary> IncludeConstantValue = 1 << 1, /// <summary> /// Includes the <c>ref</c> keyword for ref-locals. /// </summary> IncludeRef = 1 << 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; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how locals are displayed in the description of a symbol. /// </summary> [Flags] public enum SymbolDisplayLocalOptions { /// <summary> /// Shows only the name of the local. /// For example, "x". /// </summary> None = 0, /// <summary> /// Shows the type of the local in addition to its name. /// For example, "int x" in C# or "x As Integer" in Visual Basic. /// </summary> IncludeType = 1 << 0, /// <summary> /// Shows the constant value of the local, if there is one, in addition to its name. /// For example "x = 1". /// </summary> IncludeConstantValue = 1 << 1, /// <summary> /// Includes the <c>ref</c> keyword for ref-locals. /// </summary> IncludeRef = 1 << 2, } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodePartials.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. '----------------------------------------------------------------------------------------------------------- ' Contains hand-written Partial class extensions to certain of the syntax nodes (other that the ' base node SyntaxNode, which is in a different file.) '----------------------------------------------------------------------------------------------------------- Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class DocumentationCommentTriviaSyntax Friend Function GetInteriorXml() As String ' NOTE: is only used in parse tests Return DirectCast(Me.Green, InternalSyntax.DocumentationCommentTriviaSyntax).GetInteriorXml End Function End Class Partial Public Class DirectiveTriviaSyntax Private Shared ReadOnly s_hasDirectivesFunction As Func(Of SyntaxToken, Boolean) = Function(n) n.ContainsDirectives Public Function GetNextDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax Dim token = CType(MyBase.ParentTrivia.Token, SyntaxToken) Dim [next] As Boolean = False Do While (token.Kind <> SyntaxKind.None) Dim tr As SyntaxTrivia For Each tr In token.LeadingTrivia If [next] Then If tr.IsDirective Then Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax) If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then Return d End If End If Continue For End If If (tr.UnderlyingNode Is MyBase.Green) Then [next] = True End If Next token = token.GetNextToken(s_hasDirectivesFunction) Loop Return Nothing End Function Public Function GetPreviousDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax Dim token As SyntaxToken = CType(MyBase.ParentTrivia.Token, SyntaxToken) Dim [next] As Boolean = False Do While (token.Kind <> SyntaxKind.None) For Each tr In token.LeadingTrivia.Reverse() If [next] Then If tr.IsDirective Then Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax) If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then Return d End If End If ElseIf (tr.UnderlyingNode Is MyBase.Green) Then [next] = True End If Next token = token.GetPreviousToken(s_hasDirectivesFunction) Loop Return Nothing End Function End Class Partial Public Class SingleLineLambdaExpressionSyntax ''' <summary> ''' Single line subs only have a single statement. However, when binding it is convenient to have a statement list. For example, ''' dim statements are not valid in a single line lambda. However, it is nice to be able to provide semantic info about the local. ''' The only way to create locals is to have a statement list. This method is friend because the statement list should not be part ''' of the public api. ''' </summary> Friend ReadOnly Property Statements As SyntaxList(Of StatementSyntax) Get Debug.Assert(Kind = SyntaxKind.SingleLineSubLambdaExpression, "Only SingleLineSubLambdas have statements.") Debug.Assert(GetNodeSlot(1) Is Body, "SingleLineLambdaExpressionSyntax structure has changed. Update index passed to GetChildIndex.") Return New SyntaxList(Of StatementSyntax)(Body) End Get End Property End Class Partial Public Class MethodBaseSyntax Friend ReadOnly Property AsClauseInternal As AsClauseSyntax Get Select Case Me.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(Me, MethodStatementSyntax).AsClause Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader Return DirectCast(Me, LambdaHeaderSyntax).AsClause Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(Me, DeclareStatementSyntax).AsClause Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(Me, DelegateStatementSyntax).AsClause Case SyntaxKind.EventStatement Return DirectCast(Me, EventStatementSyntax).AsClause Case SyntaxKind.OperatorStatement Return DirectCast(Me, OperatorStatementSyntax).AsClause Case SyntaxKind.PropertyStatement Return DirectCast(Me, PropertyStatementSyntax).AsClause Case SyntaxKind.SubNewStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return Nothing Case Else Throw ExceptionUtilities.UnexpectedValue(Me.Kind) End Select 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. '----------------------------------------------------------------------------------------------------------- ' Contains hand-written Partial class extensions to certain of the syntax nodes (other that the ' base node SyntaxNode, which is in a different file.) '----------------------------------------------------------------------------------------------------------- Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class DocumentationCommentTriviaSyntax Friend Function GetInteriorXml() As String ' NOTE: is only used in parse tests Return DirectCast(Me.Green, InternalSyntax.DocumentationCommentTriviaSyntax).GetInteriorXml End Function End Class Partial Public Class DirectiveTriviaSyntax Private Shared ReadOnly s_hasDirectivesFunction As Func(Of SyntaxToken, Boolean) = Function(n) n.ContainsDirectives Public Function GetNextDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax Dim token = CType(MyBase.ParentTrivia.Token, SyntaxToken) Dim [next] As Boolean = False Do While (token.Kind <> SyntaxKind.None) Dim tr As SyntaxTrivia For Each tr In token.LeadingTrivia If [next] Then If tr.IsDirective Then Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax) If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then Return d End If End If Continue For End If If (tr.UnderlyingNode Is MyBase.Green) Then [next] = True End If Next token = token.GetNextToken(s_hasDirectivesFunction) Loop Return Nothing End Function Public Function GetPreviousDirective(Optional predicate As Func(Of DirectiveTriviaSyntax, Boolean) = Nothing) As DirectiveTriviaSyntax Dim token As SyntaxToken = CType(MyBase.ParentTrivia.Token, SyntaxToken) Dim [next] As Boolean = False Do While (token.Kind <> SyntaxKind.None) For Each tr In token.LeadingTrivia.Reverse() If [next] Then If tr.IsDirective Then Dim d As DirectiveTriviaSyntax = DirectCast(tr.GetStructure, DirectiveTriviaSyntax) If ((predicate Is Nothing) OrElse predicate.Invoke(d)) Then Return d End If End If ElseIf (tr.UnderlyingNode Is MyBase.Green) Then [next] = True End If Next token = token.GetPreviousToken(s_hasDirectivesFunction) Loop Return Nothing End Function End Class Partial Public Class SingleLineLambdaExpressionSyntax ''' <summary> ''' Single line subs only have a single statement. However, when binding it is convenient to have a statement list. For example, ''' dim statements are not valid in a single line lambda. However, it is nice to be able to provide semantic info about the local. ''' The only way to create locals is to have a statement list. This method is friend because the statement list should not be part ''' of the public api. ''' </summary> Friend ReadOnly Property Statements As SyntaxList(Of StatementSyntax) Get Debug.Assert(Kind = SyntaxKind.SingleLineSubLambdaExpression, "Only SingleLineSubLambdas have statements.") Debug.Assert(GetNodeSlot(1) Is Body, "SingleLineLambdaExpressionSyntax structure has changed. Update index passed to GetChildIndex.") Return New SyntaxList(Of StatementSyntax)(Body) End Get End Property End Class Partial Public Class MethodBaseSyntax Friend ReadOnly Property AsClauseInternal As AsClauseSyntax Get Select Case Me.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(Me, MethodStatementSyntax).AsClause Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader Return DirectCast(Me, LambdaHeaderSyntax).AsClause Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(Me, DeclareStatementSyntax).AsClause Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(Me, DelegateStatementSyntax).AsClause Case SyntaxKind.EventStatement Return DirectCast(Me, EventStatementSyntax).AsClause Case SyntaxKind.OperatorStatement Return DirectCast(Me, OperatorStatementSyntax).AsClause Case SyntaxKind.PropertyStatement Return DirectCast(Me, PropertyStatementSyntax).AsClause Case SyntaxKind.SubNewStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return Nothing Case Else Throw ExceptionUtilities.UnexpectedValue(Me.Kind) End Select End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedWriterCreationOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.DiaSymReader { /// <summary> /// <see cref="SymUnmanagedWriter"/> creation options. /// </summary> [Flags] internal enum SymUnmanagedWriterCreationOptions { /// <summary> /// Default options. /// </summary> Default = 0, /// <summary> /// Use environment variable MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH to locate Microsoft.DiaSymReader.Native.{platform}.dll. /// </summary> UseAlternativeLoadPath = 1 << 1, /// <summary> /// Use COM registry to locate an implementation of the writer. /// </summary> UseComRegistry = 1 << 2, /// <summary> /// Create a deterministic PDB writer. /// </summary> Deterministic = 1 << 3, } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.DiaSymReader { /// <summary> /// <see cref="SymUnmanagedWriter"/> creation options. /// </summary> [Flags] internal enum SymUnmanagedWriterCreationOptions { /// <summary> /// Default options. /// </summary> Default = 0, /// <summary> /// Use environment variable MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH to locate Microsoft.DiaSymReader.Native.{platform}.dll. /// </summary> UseAlternativeLoadPath = 1 << 1, /// <summary> /// Use COM registry to locate an implementation of the writer. /// </summary> UseComRegistry = 1 << 2, /// <summary> /// Create a deterministic PDB writer. /// </summary> Deterministic = 1 << 3, } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/Test/Resources/Core/SymbolsTests/ExplicitInterfaceImplementation/CSharpExplicitInterfaceImplementationEvents.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //csc /target:library using System; interface Interface { event Action<int> Event; } class Class : Interface { event Action<int> Interface.Event { add { } remove { } } } interface IGeneric<T> { event Action<T> Event; } class Generic<S> : IGeneric<S> { event Action<S> IGeneric<S>.Event { add { } remove { } } } class Constructed : IGeneric<int> { event Action<int> IGeneric<int>.Event { add { } remove { } } } interface IGenericInterface<T> : Interface { } //we'll see a type def for this class, a type ref for IGenericInterface<int>, //and then a type def for Interface (i.e. back and forth) class IndirectImplementation : IGenericInterface<int> { event Action<int> Interface.Event { add { } remove { } } } interface IGeneric2<T> { event Action<T> Event; } class Outer<T> { public interface IInner<U> { event Action<U> Event; } public class Inner1<A> : IGeneric2<A> //outer interface, inner type param { event Action<A> IGeneric2<A>.Event { add { } remove { } } } public class Inner2<B> : IGeneric2<T> //outer interface, outer type param { event Action<T> IGeneric2<T>.Event { add { } remove { } } } internal class Inner3<C> : IInner<C> //inner interface, inner type param { event Action<C> IInner<C>.Event { add { } remove { } } } protected class Inner4<D> : IInner<T> //inner interface, outer type param { event Action<T> IInner<T>.Event { add { } remove { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //csc /target:library using System; interface Interface { event Action<int> Event; } class Class : Interface { event Action<int> Interface.Event { add { } remove { } } } interface IGeneric<T> { event Action<T> Event; } class Generic<S> : IGeneric<S> { event Action<S> IGeneric<S>.Event { add { } remove { } } } class Constructed : IGeneric<int> { event Action<int> IGeneric<int>.Event { add { } remove { } } } interface IGenericInterface<T> : Interface { } //we'll see a type def for this class, a type ref for IGenericInterface<int>, //and then a type def for Interface (i.e. back and forth) class IndirectImplementation : IGenericInterface<int> { event Action<int> Interface.Event { add { } remove { } } } interface IGeneric2<T> { event Action<T> Event; } class Outer<T> { public interface IInner<U> { event Action<U> Event; } public class Inner1<A> : IGeneric2<A> //outer interface, inner type param { event Action<A> IGeneric2<A>.Event { add { } remove { } } } public class Inner2<B> : IGeneric2<T> //outer interface, outer type param { event Action<T> IGeneric2<T>.Event { add { } remove { } } } internal class Inner3<C> : IInner<C> //inner interface, inner type param { event Action<C> IInner<C>.Event { add { } remove { } } } protected class Inner4<D> : IInner<T> //inner interface, outer type param { event Action<T> IInner<T>.Event { add { } remove { } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/EditorFeatures/TestUtilities/EditAndContinue/DeclaratorMapDescription.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public sealed class SyntaxMapDescription { public readonly ImmutableArray<ImmutableArray<TextSpan>> OldSpans; public readonly ImmutableArray<ImmutableArray<TextSpan>> NewSpans; public SyntaxMapDescription(string oldSource, string newSource) { OldSpans = GetSpans(oldSource); NewSpans = GetSpans(newSource); Assert.Equal(OldSpans.Length, NewSpans.Length); for (var i = 0; i < OldSpans.Length; i++) { Assert.Equal(OldSpans[i].Length, NewSpans[i].Length); } } private static readonly Regex s_statementPattern = new Regex( @"[<]N[:] (?<Id>[0-9]+[.][0-9]+) [>] (?<Node>.*) [<][/]N[:] (\k<Id>) [>]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); internal static ImmutableArray<ImmutableArray<TextSpan>> GetSpans(string src) { var matches = s_statementPattern.Matches(src); var result = new List<List<TextSpan>>(); for (var i = 0; i < matches.Count; i++) { var stmt = matches[i].Groups["Node"]; var id = matches[i].Groups["Id"].Value.Split('.'); var id0 = int.Parse(id[0]); var id1 = int.Parse(id[1]); EnsureSlot(result, id0); if (result[id0] == null) { result[id0] = new List<TextSpan>(); } EnsureSlot(result[id0], id1); result[id0][id1] = new TextSpan(stmt.Index, stmt.Length); } return result.Select(r => r.AsImmutableOrEmpty()).AsImmutableOrEmpty(); } internal IEnumerable<KeyValuePair<TextSpan, TextSpan>> this[int i] { get { for (var j = 0; j < OldSpans[i].Length; j++) { yield return KeyValuePairUtil.Create(OldSpans[i][j], NewSpans[i][j]); } } } private static void EnsureSlot<T>(List<T> list, int i) { while (i >= list.Count) { list.Add(default); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public sealed class SyntaxMapDescription { public readonly ImmutableArray<ImmutableArray<TextSpan>> OldSpans; public readonly ImmutableArray<ImmutableArray<TextSpan>> NewSpans; public SyntaxMapDescription(string oldSource, string newSource) { OldSpans = GetSpans(oldSource); NewSpans = GetSpans(newSource); Assert.Equal(OldSpans.Length, NewSpans.Length); for (var i = 0; i < OldSpans.Length; i++) { Assert.Equal(OldSpans[i].Length, NewSpans[i].Length); } } private static readonly Regex s_statementPattern = new Regex( @"[<]N[:] (?<Id>[0-9]+[.][0-9]+) [>] (?<Node>.*) [<][/]N[:] (\k<Id>) [>]", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); internal static ImmutableArray<ImmutableArray<TextSpan>> GetSpans(string src) { var matches = s_statementPattern.Matches(src); var result = new List<List<TextSpan>>(); for (var i = 0; i < matches.Count; i++) { var stmt = matches[i].Groups["Node"]; var id = matches[i].Groups["Id"].Value.Split('.'); var id0 = int.Parse(id[0]); var id1 = int.Parse(id[1]); EnsureSlot(result, id0); if (result[id0] == null) { result[id0] = new List<TextSpan>(); } EnsureSlot(result[id0], id1); result[id0][id1] = new TextSpan(stmt.Index, stmt.Length); } return result.Select(r => r.AsImmutableOrEmpty()).AsImmutableOrEmpty(); } internal IEnumerable<KeyValuePair<TextSpan, TextSpan>> this[int i] { get { for (var j = 0; j < OldSpans[i].Length; j++) { yield return KeyValuePairUtil.Create(OldSpans[i][j], NewSpans[i][j]); } } } private static void EnsureSlot<T>(List<T> list, int i) { while (i >= list.Count) { list.Add(default); } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpFrameDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { [DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException] internal sealed class CSharpFrameDecoder : FrameDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol> { public CSharpFrameDecoder() : base(CSharpInstructionDecoder.Instance) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { [DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException] internal sealed class CSharpFrameDecoder : FrameDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol> { public CSharpFrameDecoder() : base(CSharpInstructionDecoder.Instance) { } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptDiagnosticAnalyzerLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(VSTypeScriptDiagnosticAnalyzerLanguageService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptDiagnosticAnalyzerLanguageService : ILanguageService { internal readonly IVSTypeScriptDiagnosticAnalyzerImplementation? Implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptDiagnosticAnalyzerLanguageService( [Import(AllowDefault = true)] IVSTypeScriptDiagnosticAnalyzerImplementation? implementation = null) { Implementation = implementation; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(VSTypeScriptDiagnosticAnalyzerLanguageService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptDiagnosticAnalyzerLanguageService : ILanguageService { internal readonly IVSTypeScriptDiagnosticAnalyzerImplementation? Implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptDiagnosticAnalyzerLanguageService( [Import(AllowDefault = true)] IVSTypeScriptDiagnosticAnalyzerImplementation? implementation = null) { Implementation = implementation; } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/CSharp/Portable/Parser/SyntaxParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal abstract partial class SyntaxParser : IDisposable { protected readonly Lexer lexer; private readonly bool _isIncremental; private readonly bool _allowModeReset; protected readonly CancellationToken cancellationToken; private LexerMode _mode; private Blender _firstBlender; private BlendedNode _currentNode; private SyntaxToken _currentToken; private ArrayElement<SyntaxToken>[] _lexedTokens; private GreenNode _prevTokenTrailingTrivia; private int _firstToken; // The position of _lexedTokens[0] (or _blendedTokens[0]). private int _tokenOffset; // The index of the current token within _lexedTokens or _blendedTokens. private int _tokenCount; private int _resetCount; private int _resetStart; private static readonly ObjectPool<BlendedNode[]> s_blendedNodesPool = new ObjectPool<BlendedNode[]>(() => new BlendedNode[32], 2); private BlendedNode[] _blendedTokens; protected SyntaxParser( Lexer lexer, LexerMode mode, CSharp.CSharpSyntaxNode oldTree, IEnumerable<TextChangeRange> changes, bool allowModeReset, bool preLexIfNotIncremental = false, CancellationToken cancellationToken = default(CancellationToken)) { this.lexer = lexer; _mode = mode; _allowModeReset = allowModeReset; this.cancellationToken = cancellationToken; _currentNode = default(BlendedNode); _isIncremental = oldTree != null; if (this.IsIncremental || allowModeReset) { _firstBlender = new Blender(lexer, oldTree, changes); _blendedTokens = s_blendedNodesPool.Allocate(); } else { _firstBlender = default(Blender); _lexedTokens = new ArrayElement<SyntaxToken>[32]; } // PreLex is not cancellable. // If we may cancel why would we aggressively lex ahead? // Cancellations in a constructor make disposing complicated // // So, if we have a real cancellation token, do not do prelexing. if (preLexIfNotIncremental && !this.IsIncremental && !cancellationToken.CanBeCanceled) { this.PreLex(); } } public void Dispose() { var blendedTokens = _blendedTokens; if (blendedTokens != null) { _blendedTokens = null; if (blendedTokens.Length < 4096) { Array.Clear(blendedTokens, 0, blendedTokens.Length); s_blendedNodesPool.Free(blendedTokens); } else { s_blendedNodesPool.ForgetTrackedObject(blendedTokens); } } } protected void ReInitialize() { _firstToken = 0; _tokenOffset = 0; _tokenCount = 0; _resetCount = 0; _resetStart = 0; _currentToken = null; _prevTokenTrailingTrivia = null; if (this.IsIncremental || _allowModeReset) { _firstBlender = new Blender(this.lexer, null, null); } } protected bool IsIncremental { get { return _isIncremental; } } private void PreLex() { // NOTE: Do not cancel in this method. It is called from the constructor. var size = Math.Min(4096, Math.Max(32, this.lexer.TextWindow.Text.Length / 2)); _lexedTokens = new ArrayElement<SyntaxToken>[size]; var lexer = this.lexer; var mode = _mode; for (int i = 0; i < size; i++) { var token = lexer.Lex(mode); this.AddLexedToken(token); if (token.Kind == SyntaxKind.EndOfFileToken) { break; } } } protected ResetPoint GetResetPoint() { var pos = CurrentTokenPosition; if (_resetCount == 0) { _resetStart = pos; // low water mark } _resetCount++; return new ResetPoint(_resetCount, _mode, pos, _prevTokenTrailingTrivia); } protected void Reset(ref ResetPoint point) { var offset = point.Position - _firstToken; Debug.Assert(offset >= 0); if (offset >= _tokenCount) { // Re-fetch tokens to the position in the reset point PeekToken(offset - _tokenOffset); // Re-calculate new offset in case tokens got shifted to the left while we were peeking. offset = point.Position - _firstToken; } _mode = point.Mode; Debug.Assert(offset >= 0 && offset < _tokenCount); _tokenOffset = offset; _currentToken = null; _currentNode = default(BlendedNode); _prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia; if (_blendedTokens != null) { // look forward for slots not holding a token for (int i = _tokenOffset; i < _tokenCount; i++) { if (_blendedTokens[i].Token == null) { // forget anything after and including any slot not holding a token _tokenCount = i; if (_tokenCount == _tokenOffset) { FetchCurrentToken(); } break; } } } } protected void Release(ref ResetPoint point) { Debug.Assert(_resetCount == point.ResetCount); _resetCount--; if (_resetCount == 0) { _resetStart = -1; } } public CSharpParseOptions Options { get { return this.lexer.Options; } } public bool IsScript { get { return Options.Kind == SourceCodeKind.Script; } } protected LexerMode Mode { get { return _mode; } set { if (_mode != value) { Debug.Assert(_allowModeReset); _mode = value; _currentToken = null; _currentNode = default(BlendedNode); _tokenCount = _tokenOffset; } } } protected CSharp.CSharpSyntaxNode CurrentNode { get { // we will fail anyways. Assert is just to catch that earlier. Debug.Assert(_blendedTokens != null); //PERF: currentNode is a BlendedNode, which is a fairly large struct. // the following code tries not to pull the whole struct into a local // we only need .Node var node = _currentNode.Node; if (node != null) { return node; } this.ReadCurrentNode(); return _currentNode.Node; } } protected SyntaxKind CurrentNodeKind { get { var cn = this.CurrentNode; return cn != null ? cn.Kind() : SyntaxKind.None; } } private void ReadCurrentNode() { if (_tokenOffset == 0) { _currentNode = _firstBlender.ReadNode(_mode); } else { _currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode); } } protected GreenNode EatNode() { // we will fail anyways. Assert is just to catch that earlier. Debug.Assert(_blendedTokens != null); // remember result var result = CurrentNode.Green; // store possible non-token in token sequence if (_tokenOffset >= _blendedTokens.Length) { this.AddTokenSlot(); } _blendedTokens[_tokenOffset++] = _currentNode; _tokenCount = _tokenOffset; // forget anything after this slot // erase current state _currentNode = default(BlendedNode); _currentToken = null; return result; } protected SyntaxToken CurrentToken { get { return _currentToken ?? (_currentToken = this.FetchCurrentToken()); } } private SyntaxToken FetchCurrentToken() { if (_tokenOffset >= _tokenCount) { this.AddNewToken(); } if (_blendedTokens != null) { return _blendedTokens[_tokenOffset].Token; } else { return _lexedTokens[_tokenOffset]; } } private void AddNewToken() { if (_blendedTokens != null) { if (_tokenCount > 0) { this.AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode)); } else { if (_currentNode.Token != null) { this.AddToken(_currentNode); } else { this.AddToken(_firstBlender.ReadToken(_mode)); } } } else { this.AddLexedToken(this.lexer.Lex(_mode)); } } // adds token to end of current token array private void AddToken(in BlendedNode tokenResult) { Debug.Assert(tokenResult.Token != null); if (_tokenCount >= _blendedTokens.Length) { this.AddTokenSlot(); } _blendedTokens[_tokenCount] = tokenResult; _tokenCount++; } private void AddLexedToken(SyntaxToken token) { Debug.Assert(token != null); if (_tokenCount >= _lexedTokens.Length) { this.AddLexedTokenSlot(); } _lexedTokens[_tokenCount].Value = token; _tokenCount++; } private void AddTokenSlot() { // shift tokens to left if we are far to the right // don't shift if reset points have fixed locked the starting point at the token in the window if (_tokenOffset > (_blendedTokens.Length >> 1) && (_resetStart == -1 || _resetStart > _firstToken)) { int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken; int shiftCount = _tokenCount - shiftOffset; Debug.Assert(shiftOffset > 0); _firstBlender = _blendedTokens[shiftOffset - 1].Blender; if (shiftCount > 0) { Array.Copy(_blendedTokens, shiftOffset, _blendedTokens, 0, shiftCount); } _firstToken += shiftOffset; _tokenCount -= shiftOffset; _tokenOffset -= shiftOffset; } else { var old = _blendedTokens; Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2); s_blendedNodesPool.ForgetTrackedObject(old, replacement: _blendedTokens); } } private void AddLexedTokenSlot() { // shift tokens to left if we are far to the right // don't shift if reset points have fixed locked the starting point at the token in the window if (_tokenOffset > (_lexedTokens.Length >> 1) && (_resetStart == -1 || _resetStart > _firstToken)) { int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken; int shiftCount = _tokenCount - shiftOffset; Debug.Assert(shiftOffset > 0); if (shiftCount > 0) { Array.Copy(_lexedTokens, shiftOffset, _lexedTokens, 0, shiftCount); } _firstToken += shiftOffset; _tokenCount -= shiftOffset; _tokenOffset -= shiftOffset; } else { var tmp = new ArrayElement<SyntaxToken>[_lexedTokens.Length * 2]; Array.Copy(_lexedTokens, tmp, _lexedTokens.Length); _lexedTokens = tmp; } } protected SyntaxToken PeekToken(int n) { Debug.Assert(n >= 0); while (_tokenOffset + n >= _tokenCount) { this.AddNewToken(); } if (_blendedTokens != null) { return _blendedTokens[_tokenOffset + n].Token; } else { return _lexedTokens[_tokenOffset + n]; } } //this method is called very frequently //we should keep it simple so that it can be inlined. protected SyntaxToken EatToken() { var ct = this.CurrentToken; MoveToNextToken(); return ct; } /// <summary> /// Returns and consumes the current token if it has the requested <paramref name="kind"/>. /// Otherwise, returns <see langword="null"/>. /// </summary> protected SyntaxToken TryEatToken(SyntaxKind kind) => this.CurrentToken.Kind == kind ? this.EatToken() : null; private void MoveToNextToken() { _prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia(); _currentToken = null; if (_blendedTokens != null) { _currentNode = default(BlendedNode); } _tokenOffset++; } protected void ForceEndOfFile() { _currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken); } //this method is called very frequently //we should keep it simple so that it can be inlined. protected SyntaxToken EatToken(SyntaxKind kind) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); var ct = this.CurrentToken; if (ct.Kind == kind) { MoveToNextToken(); return ct; } //slow part of EatToken(SyntaxKind kind) return CreateMissingToken(kind, this.CurrentToken.Kind, reportError: true); } // Consume a token if it is the right kind. Otherwise skip a token and replace it with one of the correct kind. protected SyntaxToken EatTokenAsKind(SyntaxKind expected) { Debug.Assert(SyntaxFacts.IsAnyToken(expected)); var ct = this.CurrentToken; if (ct.Kind == expected) { MoveToNextToken(); return ct; } var replacement = CreateMissingToken(expected, this.CurrentToken.Kind, reportError: true); return AddTrailingSkippedSyntax(replacement, this.EatToken()); } private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError) { // should we eat the current ParseToken's leading trivia? var token = SyntaxFactory.MissingToken(expected); if (reportError) { token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(expected, actual)); } return token; } private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError) { // should we eat the current ParseToken's leading trivia? var token = SyntaxFactory.MissingToken(expected); if (reportError) { token = AddError(token, code); } return token; } protected SyntaxToken EatToken(SyntaxKind kind, bool reportError) { if (reportError) { return EatToken(kind); } Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (this.CurrentToken.Kind != kind) { // should we eat the current ParseToken's leading trivia? return SyntaxFactory.MissingToken(kind); } else { return this.EatToken(); } } protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (this.CurrentToken.Kind != kind) { return CreateMissingToken(kind, code, reportError); } else { return this.EatToken(); } } protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind) { var token = this.CurrentToken; Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (token.Kind != kind) { token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(kind, token.Kind)); } this.MoveToNextToken(); return token; } protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args) { var token = this.EatToken(); token = WithAdditionalDiagnostics(token, MakeError(token.GetLeadingTriviaWidth(), token.Width, errorCode, args)); return token; } protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (this.CurrentToken.ContextualKind != kind) { return CreateMissingToken(kind, code, reportError); } else { return ConvertToKeyword(this.EatToken()); } } protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); var contextualKind = this.CurrentToken.ContextualKind; if (contextualKind != kind) { return CreateMissingToken(kind, contextualKind, reportError); } else { return ConvertToKeyword(this.EatToken()); } } protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width) { var code = GetExpectedTokenErrorCode(expected, actual); if (code == ErrorCode.ERR_SyntaxError || code == ErrorCode.ERR_IdentifierExpectedKW) { return new SyntaxDiagnosticInfo(offset, width, code, SyntaxFacts.GetText(expected), SyntaxFacts.GetText(actual)); } else { return new SyntaxDiagnosticInfo(offset, width, code); } } protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual) { int offset, width; this.GetDiagnosticSpanForMissingToken(out offset, out width); return this.GetExpectedTokenError(expected, actual, offset, width); } private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual) { switch (expected) { case SyntaxKind.IdentifierToken: if (SyntaxFacts.IsReservedKeyword(actual)) { return ErrorCode.ERR_IdentifierExpectedKW; // A keyword -- use special message. } else { return ErrorCode.ERR_IdentifierExpected; } case SyntaxKind.SemicolonToken: return ErrorCode.ERR_SemicolonExpected; // case TokenKind::Colon: iError = ERR_ColonExpected; break; // case TokenKind::OpenParen: iError = ERR_LparenExpected; break; case SyntaxKind.CloseParenToken: return ErrorCode.ERR_CloseParenExpected; case SyntaxKind.OpenBraceToken: return ErrorCode.ERR_LbraceExpected; case SyntaxKind.CloseBraceToken: return ErrorCode.ERR_RbraceExpected; // case TokenKind::CloseSquare: iError = ERR_CloseSquareExpected; break; default: return ErrorCode.ERR_SyntaxError; } } protected void GetDiagnosticSpanForMissingToken(out int offset, out int width) { // If the previous token has a trailing EndOfLineTrivia, // the missing token diagnostic position is moved to the // end of line containing the previous token and // its width is set to zero. // Otherwise the diagnostic offset and width is set // to the corresponding values of the current token var trivia = _prevTokenTrailingTrivia; if (trivia != null) { SyntaxList<CSharpSyntaxNode> triviaList = new SyntaxList<CSharpSyntaxNode>(trivia); bool prevTokenHasEndOfLineTrivia = triviaList.Any((int)SyntaxKind.EndOfLineTrivia); if (prevTokenHasEndOfLineTrivia) { offset = -trivia.FullWidth; width = 0; return; } } SyntaxToken ct = this.CurrentToken; offset = ct.GetLeadingTriviaWidth(); width = ct.Width; } protected virtual TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode { DiagnosticInfo[] existingDiags = node.GetDiagnostics(); int existingLength = existingDiags.Length; if (existingLength == 0) { return node.WithDiagnosticsGreen(diagnostics); } else { DiagnosticInfo[] result = new DiagnosticInfo[existingDiags.Length + diagnostics.Length]; existingDiags.CopyTo(result, 0); diagnostics.CopyTo(result, existingLength); return node.WithDiagnosticsGreen(result); } } protected TNode AddError<TNode>(TNode node, ErrorCode code) where TNode : GreenNode { return AddError(node, code, Array.Empty<object>()); } protected TNode AddError<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode { if (!node.IsMissing) { return WithAdditionalDiagnostics(node, MakeError(node, code, args)); } int offset, width; SyntaxToken token = node as SyntaxToken; if (token != null && token.ContainsSkippedText) { // This code exists to clean up an anti-pattern: // 1) an undesirable token is parsed, // 2) a desirable missing token is created and the parsed token is appended as skipped text, // 3) an error is attached to the missing token describing the problem. // If this occurs, then this.previousTokenTrailingTrivia is still populated with the trivia // of the undesirable token (now skipped text). Since the trivia no longer precedes the // node to which the error is to be attached, the computed offset will be incorrect. offset = token.GetLeadingTriviaWidth(); // Should always be zero, but at least we'll do something sensible if it's not. Debug.Assert(offset == 0, "Why are we producing a missing token that has both skipped text and leading trivia?"); width = 0; bool seenSkipped = false; foreach (var trivia in token.TrailingTrivia) { if (trivia.Kind == SyntaxKind.SkippedTokensTrivia) { seenSkipped = true; width += trivia.Width; } else if (seenSkipped) { break; } else { offset += trivia.Width; } } } else { this.GetDiagnosticSpanForMissingToken(out offset, out width); } return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args)); } protected TNode AddError<TNode>(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args)); } protected TNode AddError<TNode>(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { // assumes non-terminals will at most appear once in sub-tree int offset; FindOffset(node, location, out offset); return WithAdditionalDiagnostics(node, MakeError(offset, location.Width, code, args)); } protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode { var firstToken = node.GetFirstToken(); return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code)); } protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { var firstToken = node.GetFirstToken(); return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code, args)); } protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode { int offset; int width; GetOffsetAndWidthForLastToken(node, out offset, out width); return WithAdditionalDiagnostics(node, MakeError(offset, width, code)); } protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { int offset; int width; GetOffsetAndWidthForLastToken(node, out offset, out width); return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args)); } private static void GetOffsetAndWidthForLastToken<TNode>(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode { var lastToken = node.GetLastNonmissingToken(); offset = node.FullWidth; //advance to end of entire node width = 0; if (lastToken != null) //will be null if all tokens are missing { offset -= lastToken.FullWidth; //rewind past last token offset += lastToken.GetLeadingTriviaWidth(); //advance past last token leading trivia - now at start of last token width += lastToken.Width; } } protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code) { return new SyntaxDiagnosticInfo(offset, width, code); } protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args) { return new SyntaxDiagnosticInfo(offset, width, code, args); } protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args) { return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args); } protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args) { return new SyntaxDiagnosticInfo(code, args); } protected TNode AddLeadingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode { var oldToken = node as SyntaxToken ?? node.GetFirstToken(); var newToken = AddSkippedSyntax(oldToken, skippedSyntax, trailing: false); return SyntaxFirstTokenReplacer.Replace(node, oldToken, newToken, skippedSyntax.FullWidth); } protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax) { list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], skippedSyntax); } protected void AddTrailingSkippedSyntax<TNode>(SyntaxListBuilder<TNode> list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode { list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax); } protected TNode AddTrailingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode { var token = node as SyntaxToken; if (token != null) { return (TNode)(object)AddSkippedSyntax(token, skippedSyntax, trailing: true); } else { var lastToken = node.GetLastToken(); var newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true); return SyntaxLastTokenReplacer.Replace(node, newToken); } } /// <summary> /// Converts skippedSyntax node into tokens and adds these as trivia on the target token. /// Also adds the first error (in depth-first preorder) found in the skipped syntax tree to the target token. /// </summary> internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing) { var builder = new SyntaxListBuilder(4); // the error in we'll attach to the node SyntaxDiagnosticInfo diagnostic = null; // the position of the error within the skippedSyntax node full tree int diagnosticOffset = 0; int currentOffset = 0; foreach (var node in skippedSyntax.EnumerateNodes()) { SyntaxToken token = node as SyntaxToken; if (token != null) { builder.Add(token.GetLeadingTrivia()); if (token.Width > 0) { // separate trivia from the tokens SyntaxToken tk = token.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null); // adjust relative offsets of diagnostics attached to the token: int leadingWidth = token.GetLeadingTriviaWidth(); if (leadingWidth > 0) { var tokenDiagnostics = tk.GetDiagnostics(); for (int i = 0; i < tokenDiagnostics.Length; i++) { var d = (SyntaxDiagnosticInfo)tokenDiagnostics[i]; tokenDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset - leadingWidth, d.Width, (ErrorCode)d.Code, d.Arguments); } } builder.Add(SyntaxFactory.SkippedTokensTrivia(tk)); } else { // do not create zero-width structured trivia, GetStructure doesn't work well for them var existing = (SyntaxDiagnosticInfo)token.GetDiagnostics().FirstOrDefault(); if (existing != null) { diagnostic = existing; diagnosticOffset = currentOffset; } } builder.Add(token.GetTrailingTrivia()); currentOffset += token.FullWidth; } else if (node.ContainsDiagnostics && diagnostic == null) { // only propagate the first error to reduce noise: var existing = (SyntaxDiagnosticInfo)node.GetDiagnostics().FirstOrDefault(); if (existing != null) { diagnostic = existing; diagnosticOffset = currentOffset; } } } int triviaWidth = currentOffset; var trivia = builder.ToListNode(); // total width of everything preceding the added trivia int triviaOffset; if (trailing) { var trailingTrivia = target.GetTrailingTrivia(); triviaOffset = target.FullWidth; //added trivia is full width (before addition) target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, trivia)); } else { // Since we're adding triviaWidth before the token, we have to add that much to // the offset of each of its diagnostics. if (triviaWidth > 0) { var targetDiagnostics = target.GetDiagnostics(); for (int i = 0; i < targetDiagnostics.Length; i++) { var d = (SyntaxDiagnosticInfo)targetDiagnostics[i]; targetDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset + triviaWidth, d.Width, (ErrorCode)d.Code, d.Arguments); } } var leadingTrivia = target.GetLeadingTrivia(); target = target.TokenWithLeadingTrivia(SyntaxList.Concat(trivia, leadingTrivia)); triviaOffset = 0; //added trivia is first, so offset is zero } if (diagnostic != null) { int newOffset = triviaOffset + diagnosticOffset + diagnostic.Offset; target = WithAdditionalDiagnostics(target, new SyntaxDiagnosticInfo(newOffset, diagnostic.Width, (ErrorCode)diagnostic.Code, diagnostic.Arguments) ); } return target; } /// <summary> /// This function searches for the given location node within the subtree rooted at root node. /// If it finds it, the function computes the offset span of that child node within the root and returns true, /// otherwise it returns false. /// </summary> /// <param name="root">Root node</param> /// <param name="location">Node to search in the subtree rooted at root node</param> /// <param name="offset">Offset of the location node within the subtree rooted at child</param> /// <returns></returns> private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset) { int currentOffset = 0; offset = 0; if (root != null) { for (int i = 0, n = root.SlotCount; i < n; i++) { var child = root.GetSlot(i); if (child == null) { // ignore null slots continue; } // check if the child node is the location node if (child == location) { // Found the location node in the subtree // Initialize offset with the offset of the location node within its parent // and walk up the stack of recursive calls adding the offset of each node // within its parent offset = currentOffset; return true; } // search for the location node in the subtree rooted at child node if (this.FindOffset(child, location, out offset)) { // Found the location node in child's subtree // Add the offset of child node within its parent to offset // and continue walking up the stack offset += child.GetLeadingTriviaWidth() + currentOffset; return true; } // We didn't find the location node in the subtree rooted at child // Move on to the next child currentOffset += child.FullWidth; } } // We didn't find the location node within the subtree rooted at root node return false; } protected static SyntaxToken ConvertToKeyword(SyntaxToken token) { if (token.Kind != token.ContextualKind) { var kw = token.IsMissing ? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node) : SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node); var d = token.GetDiagnostics(); if (d != null && d.Length > 0) { kw = kw.WithDiagnosticsGreen(d); } return kw; } return token; } protected static SyntaxToken ConvertToIdentifier(SyntaxToken token) { Debug.Assert(!token.IsMissing); return SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node); } internal DirectiveStack Directives { get { return lexer.Directives; } } #nullable enable /// <remarks> /// NOTE: we are specifically diverging from dev11 to improve the user experience. /// Since treating the "async" keyword as an identifier in older language /// versions can never result in a correct program, we instead accept it as a /// keyword regardless of the language version and produce an error if the version /// is insufficient. /// </remarks> protected TNode CheckFeatureAvailability<TNode>(TNode node, MessageID feature, bool forceWarning = false) where TNode : GreenNode { LanguageVersion availableVersion = this.Options.LanguageVersion; LanguageVersion requiredVersion = feature.RequiredVersion(); // There are special error codes for some features, so handle those separately. switch (feature) { case MessageID.IDS_FeatureModuleAttrLoc: return availableVersion >= LanguageVersion.CSharp2 ? node : this.AddError(node, ErrorCode.WRN_NonECMAFeature, feature.Localize()); case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings: return availableVersion >= requiredVersion ? node : this.AddError(node, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, new CSharpRequiredLanguageVersion(requiredVersion)); } var info = feature.GetFeatureAvailabilityDiagnosticInfo(this.Options); if (info != null) { if (forceWarning) { return AddError(node, ErrorCode.WRN_ErrorOverride, info, (int)info.Code); } return AddError(node, info.Code, info.Arguments); } return node; } #nullable disable protected bool IsFeatureEnabled(MessageID feature) { return this.Options.IsFeatureEnabled(feature); } /// <summary> /// Whenever parsing in a <c>while (true)</c> loop and a bug could prevent the loop from making progress, /// this method can prevent the parsing from hanging. /// Use as: /// int tokenProgress = -1; /// while (IsMakingProgress(ref tokenProgress)) /// It should be used as a guardrail, not as a crutch, so it asserts if no progress was made. /// </summary> protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true) { var pos = CurrentTokenPosition; if (pos > lastTokenPosition) { lastTokenPosition = pos; return true; } Debug.Assert(!assertIfFalse); return false; } private int CurrentTokenPosition => _firstToken + _tokenOffset; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal abstract partial class SyntaxParser : IDisposable { protected readonly Lexer lexer; private readonly bool _isIncremental; private readonly bool _allowModeReset; protected readonly CancellationToken cancellationToken; private LexerMode _mode; private Blender _firstBlender; private BlendedNode _currentNode; private SyntaxToken _currentToken; private ArrayElement<SyntaxToken>[] _lexedTokens; private GreenNode _prevTokenTrailingTrivia; private int _firstToken; // The position of _lexedTokens[0] (or _blendedTokens[0]). private int _tokenOffset; // The index of the current token within _lexedTokens or _blendedTokens. private int _tokenCount; private int _resetCount; private int _resetStart; private static readonly ObjectPool<BlendedNode[]> s_blendedNodesPool = new ObjectPool<BlendedNode[]>(() => new BlendedNode[32], 2); private BlendedNode[] _blendedTokens; protected SyntaxParser( Lexer lexer, LexerMode mode, CSharp.CSharpSyntaxNode oldTree, IEnumerable<TextChangeRange> changes, bool allowModeReset, bool preLexIfNotIncremental = false, CancellationToken cancellationToken = default(CancellationToken)) { this.lexer = lexer; _mode = mode; _allowModeReset = allowModeReset; this.cancellationToken = cancellationToken; _currentNode = default(BlendedNode); _isIncremental = oldTree != null; if (this.IsIncremental || allowModeReset) { _firstBlender = new Blender(lexer, oldTree, changes); _blendedTokens = s_blendedNodesPool.Allocate(); } else { _firstBlender = default(Blender); _lexedTokens = new ArrayElement<SyntaxToken>[32]; } // PreLex is not cancellable. // If we may cancel why would we aggressively lex ahead? // Cancellations in a constructor make disposing complicated // // So, if we have a real cancellation token, do not do prelexing. if (preLexIfNotIncremental && !this.IsIncremental && !cancellationToken.CanBeCanceled) { this.PreLex(); } } public void Dispose() { var blendedTokens = _blendedTokens; if (blendedTokens != null) { _blendedTokens = null; if (blendedTokens.Length < 4096) { Array.Clear(blendedTokens, 0, blendedTokens.Length); s_blendedNodesPool.Free(blendedTokens); } else { s_blendedNodesPool.ForgetTrackedObject(blendedTokens); } } } protected void ReInitialize() { _firstToken = 0; _tokenOffset = 0; _tokenCount = 0; _resetCount = 0; _resetStart = 0; _currentToken = null; _prevTokenTrailingTrivia = null; if (this.IsIncremental || _allowModeReset) { _firstBlender = new Blender(this.lexer, null, null); } } protected bool IsIncremental { get { return _isIncremental; } } private void PreLex() { // NOTE: Do not cancel in this method. It is called from the constructor. var size = Math.Min(4096, Math.Max(32, this.lexer.TextWindow.Text.Length / 2)); _lexedTokens = new ArrayElement<SyntaxToken>[size]; var lexer = this.lexer; var mode = _mode; for (int i = 0; i < size; i++) { var token = lexer.Lex(mode); this.AddLexedToken(token); if (token.Kind == SyntaxKind.EndOfFileToken) { break; } } } protected ResetPoint GetResetPoint() { var pos = CurrentTokenPosition; if (_resetCount == 0) { _resetStart = pos; // low water mark } _resetCount++; return new ResetPoint(_resetCount, _mode, pos, _prevTokenTrailingTrivia); } protected void Reset(ref ResetPoint point) { var offset = point.Position - _firstToken; Debug.Assert(offset >= 0); if (offset >= _tokenCount) { // Re-fetch tokens to the position in the reset point PeekToken(offset - _tokenOffset); // Re-calculate new offset in case tokens got shifted to the left while we were peeking. offset = point.Position - _firstToken; } _mode = point.Mode; Debug.Assert(offset >= 0 && offset < _tokenCount); _tokenOffset = offset; _currentToken = null; _currentNode = default(BlendedNode); _prevTokenTrailingTrivia = point.PrevTokenTrailingTrivia; if (_blendedTokens != null) { // look forward for slots not holding a token for (int i = _tokenOffset; i < _tokenCount; i++) { if (_blendedTokens[i].Token == null) { // forget anything after and including any slot not holding a token _tokenCount = i; if (_tokenCount == _tokenOffset) { FetchCurrentToken(); } break; } } } } protected void Release(ref ResetPoint point) { Debug.Assert(_resetCount == point.ResetCount); _resetCount--; if (_resetCount == 0) { _resetStart = -1; } } public CSharpParseOptions Options { get { return this.lexer.Options; } } public bool IsScript { get { return Options.Kind == SourceCodeKind.Script; } } protected LexerMode Mode { get { return _mode; } set { if (_mode != value) { Debug.Assert(_allowModeReset); _mode = value; _currentToken = null; _currentNode = default(BlendedNode); _tokenCount = _tokenOffset; } } } protected CSharp.CSharpSyntaxNode CurrentNode { get { // we will fail anyways. Assert is just to catch that earlier. Debug.Assert(_blendedTokens != null); //PERF: currentNode is a BlendedNode, which is a fairly large struct. // the following code tries not to pull the whole struct into a local // we only need .Node var node = _currentNode.Node; if (node != null) { return node; } this.ReadCurrentNode(); return _currentNode.Node; } } protected SyntaxKind CurrentNodeKind { get { var cn = this.CurrentNode; return cn != null ? cn.Kind() : SyntaxKind.None; } } private void ReadCurrentNode() { if (_tokenOffset == 0) { _currentNode = _firstBlender.ReadNode(_mode); } else { _currentNode = _blendedTokens[_tokenOffset - 1].Blender.ReadNode(_mode); } } protected GreenNode EatNode() { // we will fail anyways. Assert is just to catch that earlier. Debug.Assert(_blendedTokens != null); // remember result var result = CurrentNode.Green; // store possible non-token in token sequence if (_tokenOffset >= _blendedTokens.Length) { this.AddTokenSlot(); } _blendedTokens[_tokenOffset++] = _currentNode; _tokenCount = _tokenOffset; // forget anything after this slot // erase current state _currentNode = default(BlendedNode); _currentToken = null; return result; } protected SyntaxToken CurrentToken { get { return _currentToken ?? (_currentToken = this.FetchCurrentToken()); } } private SyntaxToken FetchCurrentToken() { if (_tokenOffset >= _tokenCount) { this.AddNewToken(); } if (_blendedTokens != null) { return _blendedTokens[_tokenOffset].Token; } else { return _lexedTokens[_tokenOffset]; } } private void AddNewToken() { if (_blendedTokens != null) { if (_tokenCount > 0) { this.AddToken(_blendedTokens[_tokenCount - 1].Blender.ReadToken(_mode)); } else { if (_currentNode.Token != null) { this.AddToken(_currentNode); } else { this.AddToken(_firstBlender.ReadToken(_mode)); } } } else { this.AddLexedToken(this.lexer.Lex(_mode)); } } // adds token to end of current token array private void AddToken(in BlendedNode tokenResult) { Debug.Assert(tokenResult.Token != null); if (_tokenCount >= _blendedTokens.Length) { this.AddTokenSlot(); } _blendedTokens[_tokenCount] = tokenResult; _tokenCount++; } private void AddLexedToken(SyntaxToken token) { Debug.Assert(token != null); if (_tokenCount >= _lexedTokens.Length) { this.AddLexedTokenSlot(); } _lexedTokens[_tokenCount].Value = token; _tokenCount++; } private void AddTokenSlot() { // shift tokens to left if we are far to the right // don't shift if reset points have fixed locked the starting point at the token in the window if (_tokenOffset > (_blendedTokens.Length >> 1) && (_resetStart == -1 || _resetStart > _firstToken)) { int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken; int shiftCount = _tokenCount - shiftOffset; Debug.Assert(shiftOffset > 0); _firstBlender = _blendedTokens[shiftOffset - 1].Blender; if (shiftCount > 0) { Array.Copy(_blendedTokens, shiftOffset, _blendedTokens, 0, shiftCount); } _firstToken += shiftOffset; _tokenCount -= shiftOffset; _tokenOffset -= shiftOffset; } else { var old = _blendedTokens; Array.Resize(ref _blendedTokens, _blendedTokens.Length * 2); s_blendedNodesPool.ForgetTrackedObject(old, replacement: _blendedTokens); } } private void AddLexedTokenSlot() { // shift tokens to left if we are far to the right // don't shift if reset points have fixed locked the starting point at the token in the window if (_tokenOffset > (_lexedTokens.Length >> 1) && (_resetStart == -1 || _resetStart > _firstToken)) { int shiftOffset = (_resetStart == -1) ? _tokenOffset : _resetStart - _firstToken; int shiftCount = _tokenCount - shiftOffset; Debug.Assert(shiftOffset > 0); if (shiftCount > 0) { Array.Copy(_lexedTokens, shiftOffset, _lexedTokens, 0, shiftCount); } _firstToken += shiftOffset; _tokenCount -= shiftOffset; _tokenOffset -= shiftOffset; } else { var tmp = new ArrayElement<SyntaxToken>[_lexedTokens.Length * 2]; Array.Copy(_lexedTokens, tmp, _lexedTokens.Length); _lexedTokens = tmp; } } protected SyntaxToken PeekToken(int n) { Debug.Assert(n >= 0); while (_tokenOffset + n >= _tokenCount) { this.AddNewToken(); } if (_blendedTokens != null) { return _blendedTokens[_tokenOffset + n].Token; } else { return _lexedTokens[_tokenOffset + n]; } } //this method is called very frequently //we should keep it simple so that it can be inlined. protected SyntaxToken EatToken() { var ct = this.CurrentToken; MoveToNextToken(); return ct; } /// <summary> /// Returns and consumes the current token if it has the requested <paramref name="kind"/>. /// Otherwise, returns <see langword="null"/>. /// </summary> protected SyntaxToken TryEatToken(SyntaxKind kind) => this.CurrentToken.Kind == kind ? this.EatToken() : null; private void MoveToNextToken() { _prevTokenTrailingTrivia = _currentToken.GetTrailingTrivia(); _currentToken = null; if (_blendedTokens != null) { _currentNode = default(BlendedNode); } _tokenOffset++; } protected void ForceEndOfFile() { _currentToken = SyntaxFactory.Token(SyntaxKind.EndOfFileToken); } //this method is called very frequently //we should keep it simple so that it can be inlined. protected SyntaxToken EatToken(SyntaxKind kind) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); var ct = this.CurrentToken; if (ct.Kind == kind) { MoveToNextToken(); return ct; } //slow part of EatToken(SyntaxKind kind) return CreateMissingToken(kind, this.CurrentToken.Kind, reportError: true); } // Consume a token if it is the right kind. Otherwise skip a token and replace it with one of the correct kind. protected SyntaxToken EatTokenAsKind(SyntaxKind expected) { Debug.Assert(SyntaxFacts.IsAnyToken(expected)); var ct = this.CurrentToken; if (ct.Kind == expected) { MoveToNextToken(); return ct; } var replacement = CreateMissingToken(expected, this.CurrentToken.Kind, reportError: true); return AddTrailingSkippedSyntax(replacement, this.EatToken()); } private SyntaxToken CreateMissingToken(SyntaxKind expected, SyntaxKind actual, bool reportError) { // should we eat the current ParseToken's leading trivia? var token = SyntaxFactory.MissingToken(expected); if (reportError) { token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(expected, actual)); } return token; } private SyntaxToken CreateMissingToken(SyntaxKind expected, ErrorCode code, bool reportError) { // should we eat the current ParseToken's leading trivia? var token = SyntaxFactory.MissingToken(expected); if (reportError) { token = AddError(token, code); } return token; } protected SyntaxToken EatToken(SyntaxKind kind, bool reportError) { if (reportError) { return EatToken(kind); } Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (this.CurrentToken.Kind != kind) { // should we eat the current ParseToken's leading trivia? return SyntaxFactory.MissingToken(kind); } else { return this.EatToken(); } } protected SyntaxToken EatToken(SyntaxKind kind, ErrorCode code, bool reportError = true) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (this.CurrentToken.Kind != kind) { return CreateMissingToken(kind, code, reportError); } else { return this.EatToken(); } } protected SyntaxToken EatTokenWithPrejudice(SyntaxKind kind) { var token = this.CurrentToken; Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (token.Kind != kind) { token = WithAdditionalDiagnostics(token, this.GetExpectedTokenError(kind, token.Kind)); } this.MoveToNextToken(); return token; } protected SyntaxToken EatTokenWithPrejudice(ErrorCode errorCode, params object[] args) { var token = this.EatToken(); token = WithAdditionalDiagnostics(token, MakeError(token.GetLeadingTriviaWidth(), token.Width, errorCode, args)); return token; } protected SyntaxToken EatContextualToken(SyntaxKind kind, ErrorCode code, bool reportError = true) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); if (this.CurrentToken.ContextualKind != kind) { return CreateMissingToken(kind, code, reportError); } else { return ConvertToKeyword(this.EatToken()); } } protected SyntaxToken EatContextualToken(SyntaxKind kind, bool reportError = true) { Debug.Assert(SyntaxFacts.IsAnyToken(kind)); var contextualKind = this.CurrentToken.ContextualKind; if (contextualKind != kind) { return CreateMissingToken(kind, contextualKind, reportError); } else { return ConvertToKeyword(this.EatToken()); } } protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int width) { var code = GetExpectedTokenErrorCode(expected, actual); if (code == ErrorCode.ERR_SyntaxError || code == ErrorCode.ERR_IdentifierExpectedKW) { return new SyntaxDiagnosticInfo(offset, width, code, SyntaxFacts.GetText(expected), SyntaxFacts.GetText(actual)); } else { return new SyntaxDiagnosticInfo(offset, width, code); } } protected virtual SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual) { int offset, width; this.GetDiagnosticSpanForMissingToken(out offset, out width); return this.GetExpectedTokenError(expected, actual, offset, width); } private static ErrorCode GetExpectedTokenErrorCode(SyntaxKind expected, SyntaxKind actual) { switch (expected) { case SyntaxKind.IdentifierToken: if (SyntaxFacts.IsReservedKeyword(actual)) { return ErrorCode.ERR_IdentifierExpectedKW; // A keyword -- use special message. } else { return ErrorCode.ERR_IdentifierExpected; } case SyntaxKind.SemicolonToken: return ErrorCode.ERR_SemicolonExpected; // case TokenKind::Colon: iError = ERR_ColonExpected; break; // case TokenKind::OpenParen: iError = ERR_LparenExpected; break; case SyntaxKind.CloseParenToken: return ErrorCode.ERR_CloseParenExpected; case SyntaxKind.OpenBraceToken: return ErrorCode.ERR_LbraceExpected; case SyntaxKind.CloseBraceToken: return ErrorCode.ERR_RbraceExpected; // case TokenKind::CloseSquare: iError = ERR_CloseSquareExpected; break; default: return ErrorCode.ERR_SyntaxError; } } protected void GetDiagnosticSpanForMissingToken(out int offset, out int width) { // If the previous token has a trailing EndOfLineTrivia, // the missing token diagnostic position is moved to the // end of line containing the previous token and // its width is set to zero. // Otherwise the diagnostic offset and width is set // to the corresponding values of the current token var trivia = _prevTokenTrailingTrivia; if (trivia != null) { SyntaxList<CSharpSyntaxNode> triviaList = new SyntaxList<CSharpSyntaxNode>(trivia); bool prevTokenHasEndOfLineTrivia = triviaList.Any((int)SyntaxKind.EndOfLineTrivia); if (prevTokenHasEndOfLineTrivia) { offset = -trivia.FullWidth; width = 0; return; } } SyntaxToken ct = this.CurrentToken; offset = ct.GetLeadingTriviaWidth(); width = ct.Width; } protected virtual TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics) where TNode : GreenNode { DiagnosticInfo[] existingDiags = node.GetDiagnostics(); int existingLength = existingDiags.Length; if (existingLength == 0) { return node.WithDiagnosticsGreen(diagnostics); } else { DiagnosticInfo[] result = new DiagnosticInfo[existingDiags.Length + diagnostics.Length]; existingDiags.CopyTo(result, 0); diagnostics.CopyTo(result, existingLength); return node.WithDiagnosticsGreen(result); } } protected TNode AddError<TNode>(TNode node, ErrorCode code) where TNode : GreenNode { return AddError(node, code, Array.Empty<object>()); } protected TNode AddError<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : GreenNode { if (!node.IsMissing) { return WithAdditionalDiagnostics(node, MakeError(node, code, args)); } int offset, width; SyntaxToken token = node as SyntaxToken; if (token != null && token.ContainsSkippedText) { // This code exists to clean up an anti-pattern: // 1) an undesirable token is parsed, // 2) a desirable missing token is created and the parsed token is appended as skipped text, // 3) an error is attached to the missing token describing the problem. // If this occurs, then this.previousTokenTrailingTrivia is still populated with the trivia // of the undesirable token (now skipped text). Since the trivia no longer precedes the // node to which the error is to be attached, the computed offset will be incorrect. offset = token.GetLeadingTriviaWidth(); // Should always be zero, but at least we'll do something sensible if it's not. Debug.Assert(offset == 0, "Why are we producing a missing token that has both skipped text and leading trivia?"); width = 0; bool seenSkipped = false; foreach (var trivia in token.TrailingTrivia) { if (trivia.Kind == SyntaxKind.SkippedTokensTrivia) { seenSkipped = true; width += trivia.Width; } else if (seenSkipped) { break; } else { offset += trivia.Width; } } } else { this.GetDiagnosticSpanForMissingToken(out offset, out width); } return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args)); } protected TNode AddError<TNode>(TNode node, int offset, int length, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { return WithAdditionalDiagnostics(node, MakeError(offset, length, code, args)); } protected TNode AddError<TNode>(TNode node, CSharpSyntaxNode location, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { // assumes non-terminals will at most appear once in sub-tree int offset; FindOffset(node, location, out offset); return WithAdditionalDiagnostics(node, MakeError(offset, location.Width, code, args)); } protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode { var firstToken = node.GetFirstToken(); return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code)); } protected TNode AddErrorToFirstToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { var firstToken = node.GetFirstToken(); return WithAdditionalDiagnostics(node, MakeError(firstToken.GetLeadingTriviaWidth(), firstToken.Width, code, args)); } protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code) where TNode : CSharpSyntaxNode { int offset; int width; GetOffsetAndWidthForLastToken(node, out offset, out width); return WithAdditionalDiagnostics(node, MakeError(offset, width, code)); } protected TNode AddErrorToLastToken<TNode>(TNode node, ErrorCode code, params object[] args) where TNode : CSharpSyntaxNode { int offset; int width; GetOffsetAndWidthForLastToken(node, out offset, out width); return WithAdditionalDiagnostics(node, MakeError(offset, width, code, args)); } private static void GetOffsetAndWidthForLastToken<TNode>(TNode node, out int offset, out int width) where TNode : CSharpSyntaxNode { var lastToken = node.GetLastNonmissingToken(); offset = node.FullWidth; //advance to end of entire node width = 0; if (lastToken != null) //will be null if all tokens are missing { offset -= lastToken.FullWidth; //rewind past last token offset += lastToken.GetLeadingTriviaWidth(); //advance past last token leading trivia - now at start of last token width += lastToken.Width; } } protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code) { return new SyntaxDiagnosticInfo(offset, width, code); } protected static SyntaxDiagnosticInfo MakeError(int offset, int width, ErrorCode code, params object[] args) { return new SyntaxDiagnosticInfo(offset, width, code, args); } protected static SyntaxDiagnosticInfo MakeError(GreenNode node, ErrorCode code, params object[] args) { return new SyntaxDiagnosticInfo(node.GetLeadingTriviaWidth(), node.Width, code, args); } protected static SyntaxDiagnosticInfo MakeError(ErrorCode code, params object[] args) { return new SyntaxDiagnosticInfo(code, args); } protected TNode AddLeadingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode { var oldToken = node as SyntaxToken ?? node.GetFirstToken(); var newToken = AddSkippedSyntax(oldToken, skippedSyntax, trailing: false); return SyntaxFirstTokenReplacer.Replace(node, oldToken, newToken, skippedSyntax.FullWidth); } protected void AddTrailingSkippedSyntax(SyntaxListBuilder list, GreenNode skippedSyntax) { list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], skippedSyntax); } protected void AddTrailingSkippedSyntax<TNode>(SyntaxListBuilder<TNode> list, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode { list[list.Count - 1] = AddTrailingSkippedSyntax(list[list.Count - 1], skippedSyntax); } protected TNode AddTrailingSkippedSyntax<TNode>(TNode node, GreenNode skippedSyntax) where TNode : CSharpSyntaxNode { var token = node as SyntaxToken; if (token != null) { return (TNode)(object)AddSkippedSyntax(token, skippedSyntax, trailing: true); } else { var lastToken = node.GetLastToken(); var newToken = AddSkippedSyntax(lastToken, skippedSyntax, trailing: true); return SyntaxLastTokenReplacer.Replace(node, newToken); } } /// <summary> /// Converts skippedSyntax node into tokens and adds these as trivia on the target token. /// Also adds the first error (in depth-first preorder) found in the skipped syntax tree to the target token. /// </summary> internal SyntaxToken AddSkippedSyntax(SyntaxToken target, GreenNode skippedSyntax, bool trailing) { var builder = new SyntaxListBuilder(4); // the error in we'll attach to the node SyntaxDiagnosticInfo diagnostic = null; // the position of the error within the skippedSyntax node full tree int diagnosticOffset = 0; int currentOffset = 0; foreach (var node in skippedSyntax.EnumerateNodes()) { SyntaxToken token = node as SyntaxToken; if (token != null) { builder.Add(token.GetLeadingTrivia()); if (token.Width > 0) { // separate trivia from the tokens SyntaxToken tk = token.TokenWithLeadingTrivia(null).TokenWithTrailingTrivia(null); // adjust relative offsets of diagnostics attached to the token: int leadingWidth = token.GetLeadingTriviaWidth(); if (leadingWidth > 0) { var tokenDiagnostics = tk.GetDiagnostics(); for (int i = 0; i < tokenDiagnostics.Length; i++) { var d = (SyntaxDiagnosticInfo)tokenDiagnostics[i]; tokenDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset - leadingWidth, d.Width, (ErrorCode)d.Code, d.Arguments); } } builder.Add(SyntaxFactory.SkippedTokensTrivia(tk)); } else { // do not create zero-width structured trivia, GetStructure doesn't work well for them var existing = (SyntaxDiagnosticInfo)token.GetDiagnostics().FirstOrDefault(); if (existing != null) { diagnostic = existing; diagnosticOffset = currentOffset; } } builder.Add(token.GetTrailingTrivia()); currentOffset += token.FullWidth; } else if (node.ContainsDiagnostics && diagnostic == null) { // only propagate the first error to reduce noise: var existing = (SyntaxDiagnosticInfo)node.GetDiagnostics().FirstOrDefault(); if (existing != null) { diagnostic = existing; diagnosticOffset = currentOffset; } } } int triviaWidth = currentOffset; var trivia = builder.ToListNode(); // total width of everything preceding the added trivia int triviaOffset; if (trailing) { var trailingTrivia = target.GetTrailingTrivia(); triviaOffset = target.FullWidth; //added trivia is full width (before addition) target = target.TokenWithTrailingTrivia(SyntaxList.Concat(trailingTrivia, trivia)); } else { // Since we're adding triviaWidth before the token, we have to add that much to // the offset of each of its diagnostics. if (triviaWidth > 0) { var targetDiagnostics = target.GetDiagnostics(); for (int i = 0; i < targetDiagnostics.Length; i++) { var d = (SyntaxDiagnosticInfo)targetDiagnostics[i]; targetDiagnostics[i] = new SyntaxDiagnosticInfo(d.Offset + triviaWidth, d.Width, (ErrorCode)d.Code, d.Arguments); } } var leadingTrivia = target.GetLeadingTrivia(); target = target.TokenWithLeadingTrivia(SyntaxList.Concat(trivia, leadingTrivia)); triviaOffset = 0; //added trivia is first, so offset is zero } if (diagnostic != null) { int newOffset = triviaOffset + diagnosticOffset + diagnostic.Offset; target = WithAdditionalDiagnostics(target, new SyntaxDiagnosticInfo(newOffset, diagnostic.Width, (ErrorCode)diagnostic.Code, diagnostic.Arguments) ); } return target; } /// <summary> /// This function searches for the given location node within the subtree rooted at root node. /// If it finds it, the function computes the offset span of that child node within the root and returns true, /// otherwise it returns false. /// </summary> /// <param name="root">Root node</param> /// <param name="location">Node to search in the subtree rooted at root node</param> /// <param name="offset">Offset of the location node within the subtree rooted at child</param> /// <returns></returns> private bool FindOffset(GreenNode root, CSharpSyntaxNode location, out int offset) { int currentOffset = 0; offset = 0; if (root != null) { for (int i = 0, n = root.SlotCount; i < n; i++) { var child = root.GetSlot(i); if (child == null) { // ignore null slots continue; } // check if the child node is the location node if (child == location) { // Found the location node in the subtree // Initialize offset with the offset of the location node within its parent // and walk up the stack of recursive calls adding the offset of each node // within its parent offset = currentOffset; return true; } // search for the location node in the subtree rooted at child node if (this.FindOffset(child, location, out offset)) { // Found the location node in child's subtree // Add the offset of child node within its parent to offset // and continue walking up the stack offset += child.GetLeadingTriviaWidth() + currentOffset; return true; } // We didn't find the location node in the subtree rooted at child // Move on to the next child currentOffset += child.FullWidth; } } // We didn't find the location node within the subtree rooted at root node return false; } protected static SyntaxToken ConvertToKeyword(SyntaxToken token) { if (token.Kind != token.ContextualKind) { var kw = token.IsMissing ? SyntaxFactory.MissingToken(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node) : SyntaxFactory.Token(token.LeadingTrivia.Node, token.ContextualKind, token.TrailingTrivia.Node); var d = token.GetDiagnostics(); if (d != null && d.Length > 0) { kw = kw.WithDiagnosticsGreen(d); } return kw; } return token; } protected static SyntaxToken ConvertToIdentifier(SyntaxToken token) { Debug.Assert(!token.IsMissing); return SyntaxToken.Identifier(token.Kind, token.LeadingTrivia.Node, token.Text, token.ValueText, token.TrailingTrivia.Node); } internal DirectiveStack Directives { get { return lexer.Directives; } } #nullable enable /// <remarks> /// NOTE: we are specifically diverging from dev11 to improve the user experience. /// Since treating the "async" keyword as an identifier in older language /// versions can never result in a correct program, we instead accept it as a /// keyword regardless of the language version and produce an error if the version /// is insufficient. /// </remarks> protected TNode CheckFeatureAvailability<TNode>(TNode node, MessageID feature, bool forceWarning = false) where TNode : GreenNode { LanguageVersion availableVersion = this.Options.LanguageVersion; LanguageVersion requiredVersion = feature.RequiredVersion(); // There are special error codes for some features, so handle those separately. switch (feature) { case MessageID.IDS_FeatureModuleAttrLoc: return availableVersion >= LanguageVersion.CSharp2 ? node : this.AddError(node, ErrorCode.WRN_NonECMAFeature, feature.Localize()); case MessageID.IDS_FeatureAltInterpolatedVerbatimStrings: return availableVersion >= requiredVersion ? node : this.AddError(node, ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, new CSharpRequiredLanguageVersion(requiredVersion)); } var info = feature.GetFeatureAvailabilityDiagnosticInfo(this.Options); if (info != null) { if (forceWarning) { return AddError(node, ErrorCode.WRN_ErrorOverride, info, (int)info.Code); } return AddError(node, info.Code, info.Arguments); } return node; } #nullable disable protected bool IsFeatureEnabled(MessageID feature) { return this.Options.IsFeatureEnabled(feature); } /// <summary> /// Whenever parsing in a <c>while (true)</c> loop and a bug could prevent the loop from making progress, /// this method can prevent the parsing from hanging. /// Use as: /// int tokenProgress = -1; /// while (IsMakingProgress(ref tokenProgress)) /// It should be used as a guardrail, not as a crutch, so it asserts if no progress was made. /// </summary> protected bool IsMakingProgress(ref int lastTokenPosition, bool assertIfFalse = true) { var pos = CurrentTokenPosition; if (pos > lastTokenPosition) { lastTokenPosition = pos; return true; } Debug.Assert(!assertIfFalse); return false; } private int CurrentTokenPosition => _firstToken + _tokenOffset; } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/WithPrefer32Bit.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{9705A8E6-C854-4FD3-8CEA-EDBDD54C7FD8}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ConsoleApplication62</RootNamespace> <AssemblyName>ConsoleApplication62</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{9705A8E6-C854-4FD3-8CEA-EDBDD54C7FD8}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ConsoleApplication62</RootNamespace> <AssemblyName>ConsoleApplication62</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/CSharp/Portable/Symbols/Source/IndexedTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Indexed type parameters are used in place of type parameters for method signatures. There is /// a unique mapping from index to a single IndexedTypeParameterSymbol. /// /// They don't have a containing symbol or locations. /// /// They do not have constraints, variance, or attributes. /// </summary> internal sealed class IndexedTypeParameterSymbol : TypeParameterSymbol { private static TypeParameterSymbol[] s_parameterPool = Array.Empty<TypeParameterSymbol>(); private readonly int _index; private IndexedTypeParameterSymbol(int index) { _index = index; } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } internal static TypeParameterSymbol GetTypeParameter(int index) { if (index >= s_parameterPool.Length) { GrowPool(index + 1); } return s_parameterPool[index]; } private static void GrowPool(int count) { var initialPool = s_parameterPool; while (count > initialPool.Length) { var newPoolSize = ((count + 0x0F) & ~0xF); // grow in increments of 16 var newPool = new TypeParameterSymbol[newPoolSize]; Array.Copy(initialPool, newPool, initialPool.Length); for (int i = initialPool.Length; i < newPool.Length; i++) { newPool[i] = new IndexedTypeParameterSymbol(i); } Interlocked.CompareExchange(ref s_parameterPool, newPool, initialPool); // repeat if race condition occurred and someone else resized the pool before us // and the new pool is still too small initialPool = s_parameterPool; } } /// <summary> /// Create a vector of n dummy type parameters. Always reuses the same type parameter symbol /// for the same position. /// </summary> /// <param name="count"></param> /// <returns></returns> internal static ImmutableArray<TypeParameterSymbol> TakeSymbols(int count) { if (count > s_parameterPool.Length) { GrowPool(count); } ArrayBuilder<TypeParameterSymbol> builder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); for (int i = 0; i < count; i++) { builder.Add(GetTypeParameter(i)); } return builder.ToImmutableAndFree(); } internal static ImmutableArray<TypeWithAnnotations> Take(int count) { if (count > s_parameterPool.Length) { GrowPool(count); } var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); for (int i = 0; i < count; i++) { builder.Add(TypeWithAnnotations.Create(GetTypeParameter(i), NullableAnnotation.Ignored)); } return builder.ToImmutableAndFree(); } public override int Ordinal { get { return _index; } } // These object are unique (per index). internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return ReferenceEquals(this, t2); } public override int GetHashCode() { return _index; } public override VarianceKind Variance { get { return VarianceKind.None; } } public override bool HasValueTypeConstraint { get { return false; } } public override bool IsValueTypeFromConstraintTypes { get { return false; } } public override bool HasReferenceTypeConstraint { get { return false; } } public override bool IsReferenceTypeFromConstraintTypes { get { return false; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } } public override bool HasNotNullConstraint => false; internal override bool? IsNotNullable => null; public override bool HasUnmanagedTypeConstraint { get { return false; } } public override bool HasConstructorConstraint { get { return false; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override void EnsureAllConstraintsAreResolved() { } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { return null; } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { return null; } public override bool IsImplicitlyDeclared { get { 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Indexed type parameters are used in place of type parameters for method signatures. There is /// a unique mapping from index to a single IndexedTypeParameterSymbol. /// /// They don't have a containing symbol or locations. /// /// They do not have constraints, variance, or attributes. /// </summary> internal sealed class IndexedTypeParameterSymbol : TypeParameterSymbol { private static TypeParameterSymbol[] s_parameterPool = Array.Empty<TypeParameterSymbol>(); private readonly int _index; private IndexedTypeParameterSymbol(int index) { _index = index; } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } internal static TypeParameterSymbol GetTypeParameter(int index) { if (index >= s_parameterPool.Length) { GrowPool(index + 1); } return s_parameterPool[index]; } private static void GrowPool(int count) { var initialPool = s_parameterPool; while (count > initialPool.Length) { var newPoolSize = ((count + 0x0F) & ~0xF); // grow in increments of 16 var newPool = new TypeParameterSymbol[newPoolSize]; Array.Copy(initialPool, newPool, initialPool.Length); for (int i = initialPool.Length; i < newPool.Length; i++) { newPool[i] = new IndexedTypeParameterSymbol(i); } Interlocked.CompareExchange(ref s_parameterPool, newPool, initialPool); // repeat if race condition occurred and someone else resized the pool before us // and the new pool is still too small initialPool = s_parameterPool; } } /// <summary> /// Create a vector of n dummy type parameters. Always reuses the same type parameter symbol /// for the same position. /// </summary> /// <param name="count"></param> /// <returns></returns> internal static ImmutableArray<TypeParameterSymbol> TakeSymbols(int count) { if (count > s_parameterPool.Length) { GrowPool(count); } ArrayBuilder<TypeParameterSymbol> builder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); for (int i = 0; i < count; i++) { builder.Add(GetTypeParameter(i)); } return builder.ToImmutableAndFree(); } internal static ImmutableArray<TypeWithAnnotations> Take(int count) { if (count > s_parameterPool.Length) { GrowPool(count); } var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(); for (int i = 0; i < count; i++) { builder.Add(TypeWithAnnotations.Create(GetTypeParameter(i), NullableAnnotation.Ignored)); } return builder.ToImmutableAndFree(); } public override int Ordinal { get { return _index; } } // These object are unique (per index). internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return ReferenceEquals(this, t2); } public override int GetHashCode() { return _index; } public override VarianceKind Variance { get { return VarianceKind.None; } } public override bool HasValueTypeConstraint { get { return false; } } public override bool IsValueTypeFromConstraintTypes { get { return false; } } public override bool HasReferenceTypeConstraint { get { return false; } } public override bool IsReferenceTypeFromConstraintTypes { get { return false; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } } public override bool HasNotNullConstraint => false; internal override bool? IsNotNullable => null; public override bool HasUnmanagedTypeConstraint { get { return false; } } public override bool HasConstructorConstraint { get { return false; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override void EnsureAllConstraintsAreResolved() { } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { return null; } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { return null; } public override bool IsImplicitlyDeclared { get { return true; } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Compilers/Core/Portable/Text/TextChangeRange.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Represents the change to a span of text. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public readonly struct TextChangeRange : IEquatable<TextChangeRange> { /// <summary> /// The span of text before the edit which is being changed /// </summary> public TextSpan Span { get; } /// <summary> /// Width of the span after the edit. A 0 here would represent a delete /// </summary> public int NewLength { get; } internal int NewEnd => Span.Start + NewLength; /// <summary> /// Initializes a new instance of <see cref="TextChangeRange"/>. /// </summary> /// <param name="span"></param> /// <param name="newLength"></param> public TextChangeRange(TextSpan span, int newLength) : this() { if (newLength < 0) { throw new ArgumentOutOfRangeException(nameof(newLength)); } this.Span = span; this.NewLength = newLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public bool Equals(TextChangeRange other) { return other.Span == this.Span && other.NewLength == this.NewLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public override bool Equals(object? obj) { return obj is TextChangeRange range && Equals(range); } /// <summary> /// Provides hash code for current instance of <see cref="TextChangeRange"/>. /// </summary> /// <returns></returns> public override int GetHashCode() { return Hash.Combine(this.NewLength, this.Span.GetHashCode()); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are same. /// </summary> public static bool operator ==(TextChangeRange left, TextChangeRange right) { return left.Equals(right); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are different. /// </summary> public static bool operator !=(TextChangeRange left, TextChangeRange right) { return !(left == right); } /// <summary> /// An empty set of changes. /// </summary> public static IReadOnlyList<TextChangeRange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChangeRange>(); /// <summary> /// Collapse a set of <see cref="TextChangeRange"/>s into a single encompassing range. If /// the set of ranges provided is empty, an empty range is returned. /// </summary> public static TextChangeRange Collapse(IEnumerable<TextChangeRange> changes) { var diff = 0; var start = int.MaxValue; var end = 0; foreach (var change in changes) { diff += change.NewLength - change.Span.Length; if (change.Span.Start < start) { start = change.Span.Start; } if (change.Span.End > end) { end = change.Span.End; } } if (start > end) { // there were no changes. return default(TextChangeRange); } var combined = TextSpan.FromBounds(start, end); var newLen = combined.Length + diff; return new TextChangeRange(combined, newLen); } private string GetDebuggerDisplay() { return $"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})"; } public override string ToString() { return $"TextChangeRange(Span={Span}, NewLength={NewLength})"; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Represents the change to a span of text. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public readonly struct TextChangeRange : IEquatable<TextChangeRange> { /// <summary> /// The span of text before the edit which is being changed /// </summary> public TextSpan Span { get; } /// <summary> /// Width of the span after the edit. A 0 here would represent a delete /// </summary> public int NewLength { get; } internal int NewEnd => Span.Start + NewLength; /// <summary> /// Initializes a new instance of <see cref="TextChangeRange"/>. /// </summary> /// <param name="span"></param> /// <param name="newLength"></param> public TextChangeRange(TextSpan span, int newLength) : this() { if (newLength < 0) { throw new ArgumentOutOfRangeException(nameof(newLength)); } this.Span = span; this.NewLength = newLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public bool Equals(TextChangeRange other) { return other.Span == this.Span && other.NewLength == this.NewLength; } /// <summary> /// Compares current instance of <see cref="TextChangeRange"/> to another. /// </summary> public override bool Equals(object? obj) { return obj is TextChangeRange range && Equals(range); } /// <summary> /// Provides hash code for current instance of <see cref="TextChangeRange"/>. /// </summary> /// <returns></returns> public override int GetHashCode() { return Hash.Combine(this.NewLength, this.Span.GetHashCode()); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are same. /// </summary> public static bool operator ==(TextChangeRange left, TextChangeRange right) { return left.Equals(right); } /// <summary> /// Determines if two instances of <see cref="TextChangeRange"/> are different. /// </summary> public static bool operator !=(TextChangeRange left, TextChangeRange right) { return !(left == right); } /// <summary> /// An empty set of changes. /// </summary> public static IReadOnlyList<TextChangeRange> NoChanges => SpecializedCollections.EmptyReadOnlyList<TextChangeRange>(); /// <summary> /// Collapse a set of <see cref="TextChangeRange"/>s into a single encompassing range. If /// the set of ranges provided is empty, an empty range is returned. /// </summary> public static TextChangeRange Collapse(IEnumerable<TextChangeRange> changes) { var diff = 0; var start = int.MaxValue; var end = 0; foreach (var change in changes) { diff += change.NewLength - change.Span.Length; if (change.Span.Start < start) { start = change.Span.Start; } if (change.Span.End > end) { end = change.Span.End; } } if (start > end) { // there were no changes. return default(TextChangeRange); } var combined = TextSpan.FromBounds(start, end); var newLen = combined.Length + diff; return new TextChangeRange(combined, newLen); } private string GetDebuggerDisplay() { return $"new TextChangeRange(new TextSpan({Span.Start}, {Span.Length}), {NewLength})"; } public override string ToString() { return $"TextChangeRange(Span={Span}, NewLength={NewLength})"; } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Scanner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { private enum TokenKind { OpenParen = '(', CloseParen = ')', Dot = '.', Comma = ',', QuestionMark = '?', Start = char.MaxValue + 1, End, Identifier, Keyword, } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private struct Token { internal readonly TokenKind Kind; internal readonly string Text; internal readonly SyntaxKind KeywordKind; internal Token(TokenKind kind, string text = null, SyntaxKind keywordKind = SyntaxKind.None) { Kind = kind; Text = text; KeywordKind = keywordKind; } private string GetDebuggerDisplay() { return (Text == null) ? Kind.ToString() : $"{Kind}: \"{Text}\""; } } private sealed class Scanner { private readonly string _text; private int _offset; private Token _currentToken; internal Scanner(string text) { _text = text; _offset = 0; _currentToken = default(Token); } internal Token CurrentToken { get { if (_currentToken.Kind == TokenKind.Start) { throw new InvalidOperationException(); } return _currentToken; } } internal void MoveNext() { _currentToken = Scan(); } private Token Scan() { int length = _text.Length; while (_offset < length && char.IsWhiteSpace(_text[_offset])) { _offset++; } if (_offset == length) { return new Token(TokenKind.End); } int n = ScanIdentifier(); if (n > 0) { var text = _text.Substring(_offset, n); _offset += n; if (Keywords.Contains(text)) { var keywordKind = SyntaxKind.None; KeywordKinds.TryGetValue(text, out keywordKind); return new Token(TokenKind.Keyword, text, keywordKind); } return new Token(TokenKind.Identifier, text); } var c = _text[_offset++]; if (c == '[') { n = ScanIdentifier(); if (n > 0 && _offset + n < length && _text[_offset + n] == ']') { // A verbatim identifier. Treat the '[' and ']' as part // of the token, but not part of the text. var text = _text.Substring(_offset, n); _offset += n + 1; return new Token(TokenKind.Identifier, text); } } return new Token((TokenKind)c); } // Returns the number of characters in the // identifier starting at the current offset. private int ScanIdentifier() { int length = _text.Length - _offset; if (length > 0 && UnicodeCharacterUtilities.IsIdentifierStartCharacter(_text[_offset])) { int n = 1; while (n < length && UnicodeCharacterUtilities.IsIdentifierPartCharacter(_text[_offset + n])) { n++; } return n; } return 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 Roslyn.Utilities; using System; using System.Diagnostics; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { private enum TokenKind { OpenParen = '(', CloseParen = ')', Dot = '.', Comma = ',', QuestionMark = '?', Start = char.MaxValue + 1, End, Identifier, Keyword, } [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] private struct Token { internal readonly TokenKind Kind; internal readonly string Text; internal readonly SyntaxKind KeywordKind; internal Token(TokenKind kind, string text = null, SyntaxKind keywordKind = SyntaxKind.None) { Kind = kind; Text = text; KeywordKind = keywordKind; } private string GetDebuggerDisplay() { return (Text == null) ? Kind.ToString() : $"{Kind}: \"{Text}\""; } } private sealed class Scanner { private readonly string _text; private int _offset; private Token _currentToken; internal Scanner(string text) { _text = text; _offset = 0; _currentToken = default(Token); } internal Token CurrentToken { get { if (_currentToken.Kind == TokenKind.Start) { throw new InvalidOperationException(); } return _currentToken; } } internal void MoveNext() { _currentToken = Scan(); } private Token Scan() { int length = _text.Length; while (_offset < length && char.IsWhiteSpace(_text[_offset])) { _offset++; } if (_offset == length) { return new Token(TokenKind.End); } int n = ScanIdentifier(); if (n > 0) { var text = _text.Substring(_offset, n); _offset += n; if (Keywords.Contains(text)) { var keywordKind = SyntaxKind.None; KeywordKinds.TryGetValue(text, out keywordKind); return new Token(TokenKind.Keyword, text, keywordKind); } return new Token(TokenKind.Identifier, text); } var c = _text[_offset++]; if (c == '[') { n = ScanIdentifier(); if (n > 0 && _offset + n < length && _text[_offset + n] == ']') { // A verbatim identifier. Treat the '[' and ']' as part // of the token, but not part of the text. var text = _text.Substring(_offset, n); _offset += n + 1; return new Token(TokenKind.Identifier, text); } } return new Token((TokenKind)c); } // Returns the number of characters in the // identifier starting at the current offset. private int ScanIdentifier() { int length = _text.Length - _offset; if (length > 0 && UnicodeCharacterUtilities.IsIdentifierStartCharacter(_text[_offset])) { int n = 1; while (n < length && UnicodeCharacterUtilities.IsIdentifierPartCharacter(_text[_offset + n])) { n++; } return n; } return 0; } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/ExpressionEvaluator/CSharp/Source/ResultProvider/Helpers/Placeholders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { internal static class GreenNode { /// <summary> /// Required by <see cref="SyntaxKind"/>. /// </summary> public const int ListKind = 1; } } // This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed. namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal class ExtensionAttribute : Attribute { } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { internal static class GreenNode { /// <summary> /// Required by <see cref="SyntaxKind"/>. /// </summary> public const int ListKind = 1; } } // This needs to be re-defined here to avoid ambiguity, because we allow this project to target .NET 4.0 on machines without 2.0 installed. namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal class ExtensionAttribute : Attribute { } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.TriviaResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract class TriviaResult { private readonly int _endOfLineKind; private readonly int _whitespaceKind; private readonly ITriviaSavedResult _result; public TriviaResult(SemanticDocument document, ITriviaSavedResult result, int endOfLineKind, int whitespaceKind) { SemanticDocument = document; _result = result; _endOfLineKind = endOfLineKind; _whitespaceKind = whitespaceKind; } protected abstract AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode methodDefinition); protected abstract TriviaResolver GetTriviaResolver(SyntaxNode methodDefinition); public SemanticDocument SemanticDocument { get; } public async Task<OperationStatus<SemanticDocument>> ApplyAsync(GeneratedCode generatedCode, CancellationToken cancellationToken) { var document = generatedCode.SemanticDocument; var root = document.Root; var callsiteAnnotation = generatedCode.CallSiteAnnotation; var methodDefinitionAnnotation = generatedCode.MethodDefinitionAnnotation; var callsite = root.GetAnnotatedNodesAndTokens(callsiteAnnotation).SingleOrDefault().AsNode(); var method = root.GetAnnotatedNodesAndTokens(methodDefinitionAnnotation).SingleOrDefault().AsNode(); var annotationResolver = GetAnnotationResolver(callsite, method); var triviaResolver = GetTriviaResolver(method); if (annotationResolver == null || triviaResolver == null) { // bug # 6644 // this could happen in malformed code. return as it was. var status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.can_t_not_construct_final_tree); return status.With(document); } return OperationStatus.Succeeded.With( await document.WithSyntaxRootAsync(_result.RestoreTrivia(root, annotationResolver, triviaResolver), cancellationToken).ConfigureAwait(false)); } protected IEnumerable<SyntaxTrivia> FilterTriviaList(IEnumerable<SyntaxTrivia> list) { // has noisy token if (list.Any(t => t.RawKind != _endOfLineKind && t.RawKind != _whitespaceKind)) { return RemoveLeadingElasticBeforeEndOfLine(list); } // whitespace only return MergeLineBreaks(list); } protected IEnumerable<SyntaxTrivia> RemoveBlankLines(IEnumerable<SyntaxTrivia> list) { // remove any blank line at the beginning var currentLine = new List<SyntaxTrivia>(); var result = new List<SyntaxTrivia>(); var seenFirstEndOfLine = false; var i = 0; foreach (var trivia in list) { i++; if (trivia.RawKind == _endOfLineKind) { if (seenFirstEndOfLine) { // empty line. remove it if (currentLine.All(t => t.RawKind == _endOfLineKind || t.RawKind == _whitespaceKind)) { continue; } // non empty line after the first end of line. // return now return result.Concat(currentLine).Concat(list.Skip(i - 1)); } else { seenFirstEndOfLine = true; result.AddRange(currentLine); result.Add(trivia); currentLine.Clear(); continue; } } currentLine.Add(trivia); } return result.Concat(currentLine); } protected IEnumerable<SyntaxTrivia> RemoveLeadingElasticBeforeEndOfLine(IEnumerable<SyntaxTrivia> list) { var trivia = list.FirstOrDefault(); if (!trivia.IsElastic()) { return list; } var listWithoutHead = list.Skip(1); trivia = listWithoutHead.FirstOrDefault(); if (trivia.RawKind == _endOfLineKind) { return listWithoutHead; } if (trivia.IsElastic()) { return RemoveLeadingElasticBeforeEndOfLine(listWithoutHead); } return list; } protected IEnumerable<SyntaxTrivia> MergeLineBreaks(IEnumerable<SyntaxTrivia> list) { // this will make sure that it doesn't have more than two subsequent end of line // trivia without any noisy trivia var stack = new Stack<SyntaxTrivia>(); var numberOfEndOfLinesWithoutAnyNoisyTrivia = 0; foreach (var trivia in list) { if (trivia.IsElastic()) { stack.Push(trivia); continue; } if (trivia.RawKind == _endOfLineKind) { numberOfEndOfLinesWithoutAnyNoisyTrivia++; if (numberOfEndOfLinesWithoutAnyNoisyTrivia > 2) { // get rid of any whitespace trivia from stack var top = stack.Peek(); while (!top.IsElastic() && top.RawKind == _whitespaceKind) { stack.Pop(); top = stack.Peek(); } continue; } } stack.Push(trivia); } return stack.Reverse(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract class TriviaResult { private readonly int _endOfLineKind; private readonly int _whitespaceKind; private readonly ITriviaSavedResult _result; public TriviaResult(SemanticDocument document, ITriviaSavedResult result, int endOfLineKind, int whitespaceKind) { SemanticDocument = document; _result = result; _endOfLineKind = endOfLineKind; _whitespaceKind = whitespaceKind; } protected abstract AnnotationResolver GetAnnotationResolver(SyntaxNode callsite, SyntaxNode methodDefinition); protected abstract TriviaResolver GetTriviaResolver(SyntaxNode methodDefinition); public SemanticDocument SemanticDocument { get; } public async Task<OperationStatus<SemanticDocument>> ApplyAsync(GeneratedCode generatedCode, CancellationToken cancellationToken) { var document = generatedCode.SemanticDocument; var root = document.Root; var callsiteAnnotation = generatedCode.CallSiteAnnotation; var methodDefinitionAnnotation = generatedCode.MethodDefinitionAnnotation; var callsite = root.GetAnnotatedNodesAndTokens(callsiteAnnotation).SingleOrDefault().AsNode(); var method = root.GetAnnotatedNodesAndTokens(methodDefinitionAnnotation).SingleOrDefault().AsNode(); var annotationResolver = GetAnnotationResolver(callsite, method); var triviaResolver = GetTriviaResolver(method); if (annotationResolver == null || triviaResolver == null) { // bug # 6644 // this could happen in malformed code. return as it was. var status = new OperationStatus(OperationStatusFlag.None, FeaturesResources.can_t_not_construct_final_tree); return status.With(document); } return OperationStatus.Succeeded.With( await document.WithSyntaxRootAsync(_result.RestoreTrivia(root, annotationResolver, triviaResolver), cancellationToken).ConfigureAwait(false)); } protected IEnumerable<SyntaxTrivia> FilterTriviaList(IEnumerable<SyntaxTrivia> list) { // has noisy token if (list.Any(t => t.RawKind != _endOfLineKind && t.RawKind != _whitespaceKind)) { return RemoveLeadingElasticBeforeEndOfLine(list); } // whitespace only return MergeLineBreaks(list); } protected IEnumerable<SyntaxTrivia> RemoveBlankLines(IEnumerable<SyntaxTrivia> list) { // remove any blank line at the beginning var currentLine = new List<SyntaxTrivia>(); var result = new List<SyntaxTrivia>(); var seenFirstEndOfLine = false; var i = 0; foreach (var trivia in list) { i++; if (trivia.RawKind == _endOfLineKind) { if (seenFirstEndOfLine) { // empty line. remove it if (currentLine.All(t => t.RawKind == _endOfLineKind || t.RawKind == _whitespaceKind)) { continue; } // non empty line after the first end of line. // return now return result.Concat(currentLine).Concat(list.Skip(i - 1)); } else { seenFirstEndOfLine = true; result.AddRange(currentLine); result.Add(trivia); currentLine.Clear(); continue; } } currentLine.Add(trivia); } return result.Concat(currentLine); } protected IEnumerable<SyntaxTrivia> RemoveLeadingElasticBeforeEndOfLine(IEnumerable<SyntaxTrivia> list) { var trivia = list.FirstOrDefault(); if (!trivia.IsElastic()) { return list; } var listWithoutHead = list.Skip(1); trivia = listWithoutHead.FirstOrDefault(); if (trivia.RawKind == _endOfLineKind) { return listWithoutHead; } if (trivia.IsElastic()) { return RemoveLeadingElasticBeforeEndOfLine(listWithoutHead); } return list; } protected IEnumerable<SyntaxTrivia> MergeLineBreaks(IEnumerable<SyntaxTrivia> list) { // this will make sure that it doesn't have more than two subsequent end of line // trivia without any noisy trivia var stack = new Stack<SyntaxTrivia>(); var numberOfEndOfLinesWithoutAnyNoisyTrivia = 0; foreach (var trivia in list) { if (trivia.IsElastic()) { stack.Push(trivia); continue; } if (trivia.RawKind == _endOfLineKind) { numberOfEndOfLinesWithoutAnyNoisyTrivia++; if (numberOfEndOfLinesWithoutAnyNoisyTrivia > 2) { // get rid of any whitespace trivia from stack var top = stack.Peek(); while (!top.IsElastic() && top.RawKind == _whitespaceKind) { stack.Pop(); top = stack.Peek(); } continue; } } stack.Push(trivia); } return stack.Reverse(); } } } }
-1
dotnet/roslyn
56,471
Optimize InheritanceMarginGlyph construction
This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
sharwell
"2021-09-17T01:20:35Z"
"2021-09-20T18:04:19Z"
28ede84feaf2dfee3ca77d0e05ee80bd7374e49f
f6e2a28a8398fd9e5c02d9dbd8d2783156bb949f
Optimize InheritanceMarginGlyph construction. This change reduces the amount of work required to render Inheritance Margin glyphs which users did not directly interact with. * Move Inheritance Margin context menu to a separate control (lazily initialized) * Initialize Inheritance Margin glyphs in code; eliminate BAML parsing * Optimize one-way bindings for Inheritance Margin glyphs
./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.SymbolSearch.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.SymbolSearch; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int AddImport_SuggestForTypesInReferenceAssemblies { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); } } public int AddImport_SuggestForTypesInNuGetPackages { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, 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. using Microsoft.CodeAnalysis.SymbolSearch; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { public partial class AutomationObject { public int AddImport_SuggestForTypesInReferenceAssemblies { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value); } } public int AddImport_SuggestForTypesInNuGetPackages { get { return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages); } set { SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value); } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.BuildTasks</RootNamespace> <DefaultLanguage>en-US</DefaultLanguage> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion> <AssemblyVersion/> <!-- CA1819 (Properties should not return arrays) disabled as it is very common across this project. --> <NoWarn>$(NoWarn);CA1819</NoWarn> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.Build.Tasks</PackageId> <PackageDescription> The build task and targets used by MSBuild to run the C# and VB compilers. Supports using VBCSCompiler on Windows. </PackageDescription> <GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute> </PropertyGroup> <ItemGroup> <Content Include="*.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Pack>true</Pack> <BuildAction>None</BuildAction> <PackageCopyToOutput>true</PackageCopyToOutput> <PackagePath>contentFiles\any\any</PackagePath> </Content> </ItemGroup> <ItemGroup> <Compile Include="..\..\Shared\NamedPipeUtil.cs" /> <Compile Include="..\..\Shared\BuildServerConnection.cs" /> <Compile Include="..\..\Shared\RuntimeHostInfo.cs" /> <Compile Include="..\Portable\CommitHashAttribute.cs" /> <Compile Include="..\Portable\InternalUtilities\CommandLineUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\CompilerOptionParseUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\Debug.cs" Link="Debug.cs" /> <Compile Include="..\Portable\InternalUtilities\IReadOnlySet.cs" /> <Compile Include="..\Portable\InternalUtilities\NullableAttributes.cs" /> <Compile Include="..\Portable\InternalUtilities\PlatformInformation.cs" /> <Compile Include="..\Portable\InternalUtilities\ReflectionUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\RoslynString.cs" /> <Compile Include="..\Portable\InternalUtilities\UnicodeCharacterUtilities.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="ErrorString.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="System.IO.Pipes.AccessControl" Version="$(SystemIOPipesAccessControlVersion)" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" /> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.Build.Tasks.CodeAnalysis.UnitTests" /> </ItemGroup> <Import Project="..\CommandLine\CommandLine.projitems" Label="Shared" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.BuildTasks</RootNamespace> <DefaultLanguage>en-US</DefaultLanguage> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion> <AssemblyVersion/> <!-- CA1819 (Properties should not return arrays) disabled as it is very common across this project. --> <NoWarn>$(NoWarn);CA1819</NoWarn> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.Build.Tasks</PackageId> <PackageDescription> The build task and targets used by MSBuild to run the C# and VB compilers. Supports using VBCSCompiler on Windows. </PackageDescription> <GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute> </PropertyGroup> <ItemGroup> <Content Include="*.targets"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Pack>true</Pack> <BuildAction>None</BuildAction> <PackageCopyToOutput>true</PackageCopyToOutput> <PackagePath>contentFiles\any\any</PackagePath> </Content> </ItemGroup> <ItemGroup> <Compile Include="..\..\Shared\NamedPipeUtil.cs" /> <Compile Include="..\..\Shared\BuildServerConnection.cs" /> <Compile Include="..\..\Shared\RuntimeHostInfo.cs" /> <Compile Include="..\Portable\CommitHashAttribute.cs" /> <Compile Include="..\Portable\InternalUtilities\CommandLineUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\CompilerOptionParseUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\Debug.cs" Link="Debug.cs" /> <Compile Include="..\Portable\InternalUtilities\IReadOnlySet.cs" /> <Compile Include="..\Portable\InternalUtilities\NullableAttributes.cs" /> <Compile Include="..\Portable\InternalUtilities\PlatformInformation.cs" /> <Compile Include="..\Portable\InternalUtilities\ReflectionUtilities.cs" /> <Compile Include="..\Portable\InternalUtilities\RoslynString.cs" /> <Compile Include="..\Portable\InternalUtilities\UnicodeCharacterUtilities.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="ErrorString.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" ExcludeAssets="Runtime" /> <PackageReference Include="System.IO.Pipes.AccessControl" Version="$(SystemIOPipesAccessControlVersion)" Condition="'$(TargetFramework)' == 'netcoreapp3.1'" /> <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" Condition="'$(TargetFramework)' != 'netcoreapp3.1'" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.Build.Tasks.CodeAnalysis.UnitTests" /> </ItemGroup> <!-- Generate a .targets file that sets $(CompilerApiVersion) to the current Roslyn version --> <PropertyGroup> <CompilerVersionTargetsFileIntermediatePath>$(IntermediateOutputPath)Microsoft.Managed.Core.CurrentVersions.targets</CompilerVersionTargetsFileIntermediatePath> </PropertyGroup> <Target Name="GenerateCompilerVersionTargets" BeforeTargets="AssignTargetPaths" DependsOnTargets="GenerateCompilerVersionTargetsFile"> <ItemGroup> <Content Include="$(CompilerVersionTargetsFileIntermediatePath)"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <Pack>true</Pack> <BuildAction>None</BuildAction> <PackageCopyToOutput>true</PackageCopyToOutput> <PackagePath>contentFiles\any\any</PackagePath> </Content> </ItemGroup> </Target> <Target Name="GenerateCompilerVersionTargetsFile" Inputs="$(MSBuildThisFileFullPath)" Outputs="$(CompilerVersionTargetsFileIntermediatePath)"> <PropertyGroup> <CompilerApiVersion>$([System.Version]::Parse($(VersionPrefix)).Major).$([System.Version]::Parse($(VersionPrefix)).Minor)</CompilerApiVersion> <CompilerVersionTargetsFileContent> <![CDATA[<Project> <PropertyGroup> <CompilerApiVersion>roslyn$(CompilerApiVersion)</CompilerApiVersion> </PropertyGroup> </Project>]]> </CompilerVersionTargetsFileContent> </PropertyGroup> <WriteLinesToFile File="$(CompilerVersionTargetsFileIntermediatePath)" Lines="$(CompilerVersionTargetsFileContent)" Overwrite="true" /> </Target> <Import Project="..\CommandLine\CommandLine.projitems" Label="Shared" /> </Project>
1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/MSBuildTask/Microsoft.Managed.Core.targets
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- Common targets for managed compilers. --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.MapSourceRoots" AssemblyFile="$(MSBuildThisFileDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll" /> <Target Name="ShimReferencePathsWhenCommonTargetsDoesNotUnderstandReferenceAssemblies" BeforeTargets="CoreCompile" Condition="'@(ReferencePathWithRefAssemblies)' == ''"> <!-- FindReferenceAssembliesForReferences target in Common targets populate this item since dev15.3. The compiler targets may be used (via NuGet package) on earlier MSBuilds. If the ReferencePathWithRefAssemblies item is not populated, just use ReferencePaths (implementation assemblies) as they are. Since XAML inner build runs CoreCompile directly (instead of Compile target), it also doesn't invoke FindReferenceAssembliesForReferences listed in CompileDependsOn. In that case we also populate ReferencePathWithRefAssemblies with implementation assemblies. --> <ItemGroup> <ReferencePathWithRefAssemblies Include="@(ReferencePath)" /> </ItemGroup> </Target> <Target Name="_BeforeVBCSCoreCompile" DependsOnTargets="ShimReferencePathsWhenCommonTargetsDoesNotUnderstandReferenceAssemblies"> <ItemGroup Condition="'$(TargetingClr2Framework)' == 'true'"> <ReferencePathWithRefAssemblies> <EmbedInteropTypes /> </ReferencePathWithRefAssemblies> </ItemGroup> <!-- Prefer32Bit was introduced in .NET 4.5. Set it to false if we are targeting 4.0 --> <PropertyGroup Condition="('$(TargetFrameworkVersion)' == 'v4.0')"> <Prefer32Bit>false</Prefer32Bit> </PropertyGroup> <!-- TODO: Remove this ItemGroup once it has been moved to "_GenerateCompileInputs" target in Microsoft.Common.CurrentVersion.targets. https://github.com/dotnet/roslyn/issues/12223 --> <ItemGroup Condition="('$(AdditionalFileItemNames)' != '')"> <AdditionalFileItems Include="$(AdditionalFileItemNames)" /> <AdditionalFiles Include="@(%(AdditionalFileItems.Identity))" /> </ItemGroup> <PropertyGroup Condition="'$(UseSharedCompilation)' == ''"> <UseSharedCompilation>true</UseSharedCompilation> </PropertyGroup> </Target> <!-- ======================== SkipAnalyzers Support ======================== --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.ShowMessageForImplicitlySkipAnalyzers" AssemblyFile="$(MSBuildThisFileDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll" /> <Target Name="_ComputeSkipAnalyzers" BeforeTargets="CoreCompile"> <!-- First, force clear non-user facing properties '_SkipAnalyzers' and '_ImplicitlySkipAnalyzers'. --> <PropertyGroup> <_SkipAnalyzers></_SkipAnalyzers> <_ImplicitlySkipAnalyzers></_ImplicitlySkipAnalyzers> </PropertyGroup> <!-- Then, determine if '_SkipAnalyzers' needs to be 'true' based on user facing property 'RunAnalyzers'. If 'RunAnalyzers' is not set, then fallback to user facing property 'RunAnalyzersDuringBuild'. Latter property allows users to disable analyzers only for non-design time builds. Design time builds are background builds inside Visual Studio, see details here: https://github.com/dotnet/project-system/blob/main/docs/design-time-builds.md. Setting 'RunAnalyzersDuringBuild' to false, without setting 'RunAnalyzers', allows users to continue running analyzers in the background in Visual Studio while typing (i.e. intellisense), while disabling analyzer execution on explicitly invoked non-design time builds. --> <PropertyGroup Condition="'$(RunAnalyzers)' == 'false' or ('$(RunAnalyzers)' == '' and '$(RunAnalyzersDuringBuild)' == 'false')"> <_SkipAnalyzers>true</_SkipAnalyzers> </PropertyGroup> <!-- PERF: For builds which are indirectly triggered inside Visual Studio from commands such as from 'Run Tests' or 'Start Debugging', we implicitly skip analyzers and nullable analysis to speed up the build. We only do so by default when 'TreatWarningsAsErrors' is not 'true'. For the scenario where 'TreatWarningsAsErrors' is 'true', users can explicitly enable this functionality by setting 'OptimizeImplicitlyTriggeredBuild' to 'true'. NOTE: This feature is currently supported only for SDK-style projects, i.e. UsingMicrosoftNETSdk = true. --> <PropertyGroup Condition="'$(_SkipAnalyzers)' == '' and '$(IsImplicitlyTriggeredBuild)' == 'true' and '$(UsingMicrosoftNETSdk)' == 'true' and ('$(TreatWarningsAsErrors)' != 'true' or '$(OptimizeImplicitlyTriggeredBuild)' == 'true')"> <_ImplicitlySkipAnalyzers>true</_ImplicitlySkipAnalyzers> <_SkipAnalyzers>true</_SkipAnalyzers> <Features>run-nullable-analysis=never;$(Features)</Features> </PropertyGroup> <!-- Display a message to inform the users about us implicitly skipping analyzers for speeding up indirect builds. --> <ShowMessageForImplicitlySkipAnalyzers Condition="'$(_ImplicitlySkipAnalyzers)' == 'true'"/> <!-- Semaphore file to indicate the time stamp for last build with skipAnalyzers flag. --> <PropertyGroup> <_LastBuildWithSkipAnalyzers>$(IntermediateOutputPath)$(MSBuildProjectFile).BuildWithSkipAnalyzers</_LastBuildWithSkipAnalyzers> </PropertyGroup> <!-- '_LastBuildWithSkipAnalyzers' semaphore file, if exists, is passed as custom additional file input to builds without skipAnalyzers flag to ensure correct incremental builds. Additionally, we need to pass this file as an 'UpToDateCheckInput' item with 'Kind = ImplicitBuild' for project system's fast-upto-date check to work correctly. See https://github.com/dotnet/project-system/issues/7290 for details. --> <ItemGroup Condition="Exists('$(_LastBuildWithSkipAnalyzers)')"> <CustomAdditionalCompileInputs Include="$(_LastBuildWithSkipAnalyzers)" Condition="'$(_SkipAnalyzers)' != 'true'"/> <UpToDateCheckInput Include="$(_LastBuildWithSkipAnalyzers)" Kind="ImplicitBuild"/> </ItemGroup> </Target> <!-- We touch and create a semaphore file after build to indicate the time stamp for last build with skipAnalyzers flag. --> <Target Name="_TouchLastBuildWithSkipAnalyzers" Condition="'$(_SkipAnalyzers)' == 'true'" AfterTargets="CoreCompile"> <Touch AlwaysCreate="true" Files="$(_LastBuildWithSkipAnalyzers)"/> </Target> <!-- ======================== .editorconfig Support ======================== --> <ItemGroup> <_AllDirectoriesAbove Include="@(Compile->GetPathsOfAllDirectoriesAbove())" Condition="'$(DiscoverEditorConfigFiles)' != 'false' or '$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'" /> <!-- Work around a GetPathsOfAllDirectoriesAbove() bug where it can return multiple equivalent paths when the compilation includes linked files with relative paths - https://github.com/microsoft/msbuild/issues/4392 --> <PotentialEditorConfigFiles Include="@(_AllDirectoriesAbove->'%(FullPath)'->Distinct()->Combine('.editorconfig'))" Condition="'$(DiscoverEditorConfigFiles)' != 'false'" /> <EditorConfigFiles Include="@(PotentialEditorConfigFiles->Exists())" Condition="'$(DiscoverEditorConfigFiles)' != 'false'" /> <GlobalAnalyzerConfigFiles Include="@(_AllDirectoriesAbove->'%(FullPath)'->Distinct()->Combine('.globalconfig'))" Condition="'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'" /> <EditorConfigFiles Include="@(GlobalAnalyzerConfigFiles->Exists())" Condition="'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'" /> </ItemGroup> <!-- ======================== Property/metadata global .editorconfig Support ======================== Generates a global editor config that contains the evaluation of requested MSBuild properties and item metadata Requested properties/items are requested via item groups like: <CompilerVisibleProperty Include="PropertyNameToEval" /> <CompilerVisibleItemMetadata Include="ItemType" MetadataName="MetadataToRetrieve" /> --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.GenerateMSBuildEditorConfig" AssemblyFile="$(MSBuildThisFileDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll" /> <Target Name="GenerateMSBuildEditorConfigFile" BeforeTargets="BeforeCompile;CoreCompile" DependsOnTargets="PrepareForBuild;GenerateMSBuildEditorConfigFileShouldRun;GenerateMSBuildEditorConfigFileCore" /> <Target Name="GenerateMSBuildEditorConfigFileShouldRun"> <PropertyGroup> <GeneratedMSBuildEditorConfigFile Condition="'$(GeneratedMSBuildEditorConfigFile)' == ''">$(IntermediateOutputPath)$(MSBuildProjectName).GeneratedMSBuildEditorConfig.editorconfig</GeneratedMSBuildEditorConfigFile> <GenerateMSBuildEditorConfigFile Condition="'$(GenerateMSBuildEditorConfigFile)' == ''">true</GenerateMSBuildEditorConfigFile> <_GeneratedEditorConfigHasItems Condition="'@(CompilerVisibleItemMetadata->Count())' != '0'">true</_GeneratedEditorConfigHasItems> <_GeneratedEditorConfigShouldRun Condition="'$(GenerateMSBuildEditorConfigFile)' == 'true' and ('$(_GeneratedEditorConfigHasItems)' == 'true' or '@(CompilerVisibleProperty->Count())' != '0')">true</_GeneratedEditorConfigShouldRun> </PropertyGroup> </Target> <Target Name="GenerateMSBuildEditorConfigFileCore" Condition="'$(_GeneratedEditorConfigShouldRun)' == 'true'" Outputs="$(GeneratedMSBuildEditorConfigFile)"> <ItemGroup> <!-- Collect requested properties, and eval their value --> <_GeneratedEditorConfigProperty Include="@(CompilerVisibleProperty)"> <Value>$(%(CompilerVisibleProperty.Identity))</Value> </_GeneratedEditorConfigProperty> <!-- Collect the requested items and remember which metadata is wanted --> <_GeneratedEditorConfigMetadata Include="@(%(CompilerVisibleItemMetadata.Identity))" Condition="'$(_GeneratedEditorConfigHasItems)' == 'true'"> <ItemType>%(Identity)</ItemType> <MetadataName>%(CompilerVisibleItemMetadata.MetadataName)</MetadataName> </_GeneratedEditorConfigMetadata> <!-- Record that we'll write a file, and add it to the analyzerconfig inputs --> <FileWrites Include="$(GeneratedMSBuildEditorConfigFile)" /> <EditorConfigFiles Include="$(GeneratedMSBuildEditorConfigFile)" /> </ItemGroup> <!-- Transform the collected properties and items into an editor config file --> <GenerateMSBuildEditorConfig PropertyItems="@(_GeneratedEditorConfigProperty)" MetadataItems="@(_GeneratedEditorConfigMetadata)" FileName="$(GeneratedMSBuildEditorConfigFile)"> </GenerateMSBuildEditorConfig> </Target> <!-- ======================== DeterministicSourcePaths ======================== Unless specified otherwise enable deterministic source root (PathMap) when building deterministically on CI server, but not for local builds. In order for the debugger to find source files when debugging a locally built binary the PDB must contain original, unmapped local paths. --> <PropertyGroup> <DeterministicSourcePaths Condition="'$(DeterministicSourcePaths)' == '' and '$(Deterministic)' == 'true' and '$(ContinuousIntegrationBuild)' == 'true'">true</DeterministicSourcePaths> </PropertyGroup> <!-- ========== SourceRoot ========== All source files of the project are expected to be located under one of the directories specified by SourceRoot item group. This target collects all SourceRoots from various sources. This target calculates final local path for each SourceRoot and sets SourceRoot.MappedPath metadata accordingly. The final path is a path with deterministic prefix when DeterministicSourcePaths is true, and the original path otherwise. In addition, the target validates and deduplicates the SourceRoot items. InitializeSourceControlInformation is an msbuild target that ensures the SourceRoot items are populated from source control. The target is available only if SourceControlInformationFeatureSupported is true. A consumer of SourceRoot.MappedPath metadata, such as Source Link generator, shall depend on this target. --> <Target Name="InitializeSourceRootMappedPaths" DependsOnTargets="_InitializeSourceRootMappedPathsFromSourceControl" Returns="@(SourceRoot)"> <ItemGroup Condition="'@(_MappedSourceRoot)' != ''"> <_MappedSourceRoot Remove="@(_MappedSourceRoot)" /> </ItemGroup> <Microsoft.CodeAnalysis.BuildTasks.MapSourceRoots SourceRoots="@(SourceRoot)" Deterministic="$(DeterministicSourcePaths)"> <Output TaskParameter="MappedSourceRoots" ItemName="_MappedSourceRoot" /> </Microsoft.CodeAnalysis.BuildTasks.MapSourceRoots> <ItemGroup> <SourceRoot Remove="@(SourceRoot)" /> <SourceRoot Include="@(_MappedSourceRoot)" /> </ItemGroup> </Target> <!-- Declare that target InitializeSourceRootMappedPaths that populates MappedPaths metadata on SourceRoot items is available. --> <PropertyGroup> <SourceRootMappedPathsFeatureSupported>true</SourceRootMappedPathsFeatureSupported> </PropertyGroup> <!-- If InitializeSourceControlInformation target isn't supported, we just continue without invoking that synchronization target. We'll proceed with SourceRoot (and other source control properties) provided by the user (or blank). --> <Target Name="_InitializeSourceRootMappedPathsFromSourceControl" DependsOnTargets="InitializeSourceControlInformation" Condition="'$(SourceControlInformationFeatureSupported)' == 'true'" /> <!-- ======= PathMap ======= If DeterministicSourcePaths is true sets PathMap based on SourceRoot.MappedPaths. This target requires SourceRoot to be initialized in order to calculate the PathMap. If SourceRoot doesn't contain any top-level roots an error is reported. --> <Target Name="_SetPathMapFromSourceRoots" DependsOnTargets="InitializeSourceRootMappedPaths" BeforeTargets="CoreCompile" Condition="'$(DeterministicSourcePaths)' == 'true'"> <ItemGroup> <_TopLevelSourceRoot Include="@(SourceRoot)" Condition="'%(SourceRoot.NestedRoot)' == ''"> <EscapedKey>$([MSBuild]::ValueOrDefault('%(Identity)', '').Replace(',', ',,').Replace('=', '=='))</EscapedKey> <EscapedValue>$([MSBuild]::ValueOrDefault('%(MappedPath)', '').Replace(',', ',,').Replace('=', '=='))</EscapedValue> </_TopLevelSourceRoot> </ItemGroup> <PropertyGroup Condition="'@(_TopLevelSourceRoot)' != ''"> <!-- Prepend the SourceRoot.MappedPath values to PathMap, if it already has a value. For each emitted source path the compiler applies the first mapping that matches the path. PathMap values set previously will thus only be applied if the mapping provided by SourceRoot.MappedPath doesn't match. Since SourceRoot.MappedPath is also used by SourceLink preferring it over manually set PathMap ensures that PathMap is consistent with SourceLink. --> <PathMap>@(_TopLevelSourceRoot->'%(EscapedKey)=%(EscapedValue)', ','),$(PathMap)</PathMap> </PropertyGroup> </Target> <!-- ======= CopyAdditionalFiles ======= If a user requests that any @(AdditionalFiles) items are copied to the output directory we add them to the @(None) group to ensure they will be copied. --> <Target Name="CopyAdditionalFiles" BeforeTargets="AssignTargetPaths"> <ItemGroup> <None Include="@(AdditionalFiles)" Condition="'%(AdditionalFiles.CopyToOutputDirectory)' != ''" /> </ItemGroup> </Target> <!-- ======================== CompilerGeneratedFilesOutputPath ======================== Controls output of generated files. CompilerGeneratedFilesOutputPath controls the location the files will be output to. The compiler will not emit any generated files when the path is empty, and defaults to a /generated directory in $(IntermediateOutputPath) if $(IntermediateOutputPath) has a value. EmitCompilerGeneratedFiles allows the user to control if anything is emitted by clearing the property when not true. When EmitCompilerGeneratedFiles is true, we ensure that CompilerGeneatedFilesOutputPath has a value and issue a warning if not. We will create CompilerGeneratedFilesOutputPath if it does not exist. --> <PropertyGroup> <EmitCompilerGeneratedFiles Condition="'$(EmitCompilerGeneratedFiles)' == ''">false</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath Condition="'$(EmitCompilerGeneratedFiles)' != 'true'"></CompilerGeneratedFilesOutputPath> <CompilerGeneratedFilesOutputPath Condition="'$(EmitCompilerGeneratedFiles)' == 'true' and '$(CompilerGeneratedFilesOutputPath)' == '' and '$(IntermediateOutputPath)' != ''">$(IntermediateOutputPath)/generated</CompilerGeneratedFilesOutputPath> </PropertyGroup> <Target Name="CreateCompilerGeneratedFilesOutputPath" BeforeTargets="CoreCompile" Condition="'$(EmitCompilerGeneratedFiles)' == 'true' and !('$(DesignTimeBuild)' == 'true' OR '$(BuildingProject)' != 'true')"> <Warning Condition="'$(CompilerGeneratedFilesOutputPath)' == ''" Text="EmitCompilerGeneratedFiles was true, but no CompilerGeneratedFilesOutputPath was provided. CompilerGeneratedFilesOutputPath must be set in order to emit generated files." /> <MakeDir Condition="'$(CompilerGeneratedFilesOutputPath)' != ''" Directories="$(CompilerGeneratedFilesOutputPath)" /> </Target> <!-- ======================== Component Debugger Support ======================== Add the specified VS capability if a user indicates this project supports component debugging --> <ItemGroup> <ProjectCapability Include="RoslynComponent" Condition="'$(IsRoslynComponent)' == 'true'"/> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- Common targets for managed compilers. --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.MapSourceRoots" AssemblyFile="$(MSBuildThisFileDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll" /> <Import Project="Microsoft.Managed.Core.CurrentVersions.targets" /> <Target Name="ShimReferencePathsWhenCommonTargetsDoesNotUnderstandReferenceAssemblies" BeforeTargets="CoreCompile" Condition="'@(ReferencePathWithRefAssemblies)' == ''"> <!-- FindReferenceAssembliesForReferences target in Common targets populate this item since dev15.3. The compiler targets may be used (via NuGet package) on earlier MSBuilds. If the ReferencePathWithRefAssemblies item is not populated, just use ReferencePaths (implementation assemblies) as they are. Since XAML inner build runs CoreCompile directly (instead of Compile target), it also doesn't invoke FindReferenceAssembliesForReferences listed in CompileDependsOn. In that case we also populate ReferencePathWithRefAssemblies with implementation assemblies. --> <ItemGroup> <ReferencePathWithRefAssemblies Include="@(ReferencePath)" /> </ItemGroup> </Target> <Target Name="_BeforeVBCSCoreCompile" DependsOnTargets="ShimReferencePathsWhenCommonTargetsDoesNotUnderstandReferenceAssemblies"> <ItemGroup Condition="'$(TargetingClr2Framework)' == 'true'"> <ReferencePathWithRefAssemblies> <EmbedInteropTypes /> </ReferencePathWithRefAssemblies> </ItemGroup> <!-- Prefer32Bit was introduced in .NET 4.5. Set it to false if we are targeting 4.0 --> <PropertyGroup Condition="('$(TargetFrameworkVersion)' == 'v4.0')"> <Prefer32Bit>false</Prefer32Bit> </PropertyGroup> <!-- TODO: Remove this ItemGroup once it has been moved to "_GenerateCompileInputs" target in Microsoft.Common.CurrentVersion.targets. https://github.com/dotnet/roslyn/issues/12223 --> <ItemGroup Condition="('$(AdditionalFileItemNames)' != '')"> <AdditionalFileItems Include="$(AdditionalFileItemNames)" /> <AdditionalFiles Include="@(%(AdditionalFileItems.Identity))" /> </ItemGroup> <PropertyGroup Condition="'$(UseSharedCompilation)' == ''"> <UseSharedCompilation>true</UseSharedCompilation> </PropertyGroup> </Target> <!-- ======================== SkipAnalyzers Support ======================== --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.ShowMessageForImplicitlySkipAnalyzers" AssemblyFile="$(MSBuildThisFileDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll" /> <Target Name="_ComputeSkipAnalyzers" BeforeTargets="CoreCompile"> <!-- First, force clear non-user facing properties '_SkipAnalyzers' and '_ImplicitlySkipAnalyzers'. --> <PropertyGroup> <_SkipAnalyzers></_SkipAnalyzers> <_ImplicitlySkipAnalyzers></_ImplicitlySkipAnalyzers> </PropertyGroup> <!-- Then, determine if '_SkipAnalyzers' needs to be 'true' based on user facing property 'RunAnalyzers'. If 'RunAnalyzers' is not set, then fallback to user facing property 'RunAnalyzersDuringBuild'. Latter property allows users to disable analyzers only for non-design time builds. Design time builds are background builds inside Visual Studio, see details here: https://github.com/dotnet/project-system/blob/main/docs/design-time-builds.md. Setting 'RunAnalyzersDuringBuild' to false, without setting 'RunAnalyzers', allows users to continue running analyzers in the background in Visual Studio while typing (i.e. intellisense), while disabling analyzer execution on explicitly invoked non-design time builds. --> <PropertyGroup Condition="'$(RunAnalyzers)' == 'false' or ('$(RunAnalyzers)' == '' and '$(RunAnalyzersDuringBuild)' == 'false')"> <_SkipAnalyzers>true</_SkipAnalyzers> </PropertyGroup> <!-- PERF: For builds which are indirectly triggered inside Visual Studio from commands such as from 'Run Tests' or 'Start Debugging', we implicitly skip analyzers and nullable analysis to speed up the build. We only do so by default when 'TreatWarningsAsErrors' is not 'true'. For the scenario where 'TreatWarningsAsErrors' is 'true', users can explicitly enable this functionality by setting 'OptimizeImplicitlyTriggeredBuild' to 'true'. NOTE: This feature is currently supported only for SDK-style projects, i.e. UsingMicrosoftNETSdk = true. --> <PropertyGroup Condition="'$(_SkipAnalyzers)' == '' and '$(IsImplicitlyTriggeredBuild)' == 'true' and '$(UsingMicrosoftNETSdk)' == 'true' and ('$(TreatWarningsAsErrors)' != 'true' or '$(OptimizeImplicitlyTriggeredBuild)' == 'true')"> <_ImplicitlySkipAnalyzers>true</_ImplicitlySkipAnalyzers> <_SkipAnalyzers>true</_SkipAnalyzers> <Features>run-nullable-analysis=never;$(Features)</Features> </PropertyGroup> <!-- Display a message to inform the users about us implicitly skipping analyzers for speeding up indirect builds. --> <ShowMessageForImplicitlySkipAnalyzers Condition="'$(_ImplicitlySkipAnalyzers)' == 'true'"/> <!-- Semaphore file to indicate the time stamp for last build with skipAnalyzers flag. --> <PropertyGroup> <_LastBuildWithSkipAnalyzers>$(IntermediateOutputPath)$(MSBuildProjectFile).BuildWithSkipAnalyzers</_LastBuildWithSkipAnalyzers> </PropertyGroup> <!-- '_LastBuildWithSkipAnalyzers' semaphore file, if exists, is passed as custom additional file input to builds without skipAnalyzers flag to ensure correct incremental builds. Additionally, we need to pass this file as an 'UpToDateCheckInput' item with 'Kind = ImplicitBuild' for project system's fast-upto-date check to work correctly. See https://github.com/dotnet/project-system/issues/7290 for details. --> <ItemGroup Condition="Exists('$(_LastBuildWithSkipAnalyzers)')"> <CustomAdditionalCompileInputs Include="$(_LastBuildWithSkipAnalyzers)" Condition="'$(_SkipAnalyzers)' != 'true'"/> <UpToDateCheckInput Include="$(_LastBuildWithSkipAnalyzers)" Kind="ImplicitBuild"/> </ItemGroup> </Target> <!-- We touch and create a semaphore file after build to indicate the time stamp for last build with skipAnalyzers flag. --> <Target Name="_TouchLastBuildWithSkipAnalyzers" Condition="'$(_SkipAnalyzers)' == 'true'" AfterTargets="CoreCompile"> <Touch AlwaysCreate="true" Files="$(_LastBuildWithSkipAnalyzers)"/> </Target> <!-- ======================== .editorconfig Support ======================== --> <ItemGroup> <_AllDirectoriesAbove Include="@(Compile->GetPathsOfAllDirectoriesAbove())" Condition="'$(DiscoverEditorConfigFiles)' != 'false' or '$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'" /> <!-- Work around a GetPathsOfAllDirectoriesAbove() bug where it can return multiple equivalent paths when the compilation includes linked files with relative paths - https://github.com/microsoft/msbuild/issues/4392 --> <PotentialEditorConfigFiles Include="@(_AllDirectoriesAbove->'%(FullPath)'->Distinct()->Combine('.editorconfig'))" Condition="'$(DiscoverEditorConfigFiles)' != 'false'" /> <EditorConfigFiles Include="@(PotentialEditorConfigFiles->Exists())" Condition="'$(DiscoverEditorConfigFiles)' != 'false'" /> <GlobalAnalyzerConfigFiles Include="@(_AllDirectoriesAbove->'%(FullPath)'->Distinct()->Combine('.globalconfig'))" Condition="'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'" /> <EditorConfigFiles Include="@(GlobalAnalyzerConfigFiles->Exists())" Condition="'$(DiscoverGlobalAnalyzerConfigFiles)' != 'false'" /> </ItemGroup> <!-- ======================== Property/metadata global .editorconfig Support ======================== Generates a global editor config that contains the evaluation of requested MSBuild properties and item metadata Requested properties/items are requested via item groups like: <CompilerVisibleProperty Include="PropertyNameToEval" /> <CompilerVisibleItemMetadata Include="ItemType" MetadataName="MetadataToRetrieve" /> --> <UsingTask TaskName="Microsoft.CodeAnalysis.BuildTasks.GenerateMSBuildEditorConfig" AssemblyFile="$(MSBuildThisFileDirectory)Microsoft.Build.Tasks.CodeAnalysis.dll" /> <Target Name="GenerateMSBuildEditorConfigFile" BeforeTargets="BeforeCompile;CoreCompile" DependsOnTargets="PrepareForBuild;GenerateMSBuildEditorConfigFileShouldRun;GenerateMSBuildEditorConfigFileCore" /> <Target Name="GenerateMSBuildEditorConfigFileShouldRun"> <PropertyGroup> <GeneratedMSBuildEditorConfigFile Condition="'$(GeneratedMSBuildEditorConfigFile)' == ''">$(IntermediateOutputPath)$(MSBuildProjectName).GeneratedMSBuildEditorConfig.editorconfig</GeneratedMSBuildEditorConfigFile> <GenerateMSBuildEditorConfigFile Condition="'$(GenerateMSBuildEditorConfigFile)' == ''">true</GenerateMSBuildEditorConfigFile> <_GeneratedEditorConfigHasItems Condition="'@(CompilerVisibleItemMetadata->Count())' != '0'">true</_GeneratedEditorConfigHasItems> <_GeneratedEditorConfigShouldRun Condition="'$(GenerateMSBuildEditorConfigFile)' == 'true' and ('$(_GeneratedEditorConfigHasItems)' == 'true' or '@(CompilerVisibleProperty->Count())' != '0')">true</_GeneratedEditorConfigShouldRun> </PropertyGroup> </Target> <Target Name="GenerateMSBuildEditorConfigFileCore" Condition="'$(_GeneratedEditorConfigShouldRun)' == 'true'" Outputs="$(GeneratedMSBuildEditorConfigFile)"> <ItemGroup> <!-- Collect requested properties, and eval their value --> <_GeneratedEditorConfigProperty Include="@(CompilerVisibleProperty)"> <Value>$(%(CompilerVisibleProperty.Identity))</Value> </_GeneratedEditorConfigProperty> <!-- Collect the requested items and remember which metadata is wanted --> <_GeneratedEditorConfigMetadata Include="@(%(CompilerVisibleItemMetadata.Identity))" Condition="'$(_GeneratedEditorConfigHasItems)' == 'true'"> <ItemType>%(Identity)</ItemType> <MetadataName>%(CompilerVisibleItemMetadata.MetadataName)</MetadataName> </_GeneratedEditorConfigMetadata> <!-- Record that we'll write a file, and add it to the analyzerconfig inputs --> <FileWrites Include="$(GeneratedMSBuildEditorConfigFile)" /> <EditorConfigFiles Include="$(GeneratedMSBuildEditorConfigFile)" /> </ItemGroup> <!-- Transform the collected properties and items into an editor config file --> <GenerateMSBuildEditorConfig PropertyItems="@(_GeneratedEditorConfigProperty)" MetadataItems="@(_GeneratedEditorConfigMetadata)" FileName="$(GeneratedMSBuildEditorConfigFile)"> </GenerateMSBuildEditorConfig> </Target> <!-- ======================== DeterministicSourcePaths ======================== Unless specified otherwise enable deterministic source root (PathMap) when building deterministically on CI server, but not for local builds. In order for the debugger to find source files when debugging a locally built binary the PDB must contain original, unmapped local paths. --> <PropertyGroup> <DeterministicSourcePaths Condition="'$(DeterministicSourcePaths)' == '' and '$(Deterministic)' == 'true' and '$(ContinuousIntegrationBuild)' == 'true'">true</DeterministicSourcePaths> </PropertyGroup> <!-- ========== SourceRoot ========== All source files of the project are expected to be located under one of the directories specified by SourceRoot item group. This target collects all SourceRoots from various sources. This target calculates final local path for each SourceRoot and sets SourceRoot.MappedPath metadata accordingly. The final path is a path with deterministic prefix when DeterministicSourcePaths is true, and the original path otherwise. In addition, the target validates and deduplicates the SourceRoot items. InitializeSourceControlInformation is an msbuild target that ensures the SourceRoot items are populated from source control. The target is available only if SourceControlInformationFeatureSupported is true. A consumer of SourceRoot.MappedPath metadata, such as Source Link generator, shall depend on this target. --> <Target Name="InitializeSourceRootMappedPaths" DependsOnTargets="_InitializeSourceRootMappedPathsFromSourceControl" Returns="@(SourceRoot)"> <ItemGroup Condition="'@(_MappedSourceRoot)' != ''"> <_MappedSourceRoot Remove="@(_MappedSourceRoot)" /> </ItemGroup> <Microsoft.CodeAnalysis.BuildTasks.MapSourceRoots SourceRoots="@(SourceRoot)" Deterministic="$(DeterministicSourcePaths)"> <Output TaskParameter="MappedSourceRoots" ItemName="_MappedSourceRoot" /> </Microsoft.CodeAnalysis.BuildTasks.MapSourceRoots> <ItemGroup> <SourceRoot Remove="@(SourceRoot)" /> <SourceRoot Include="@(_MappedSourceRoot)" /> </ItemGroup> </Target> <!-- Declare that target InitializeSourceRootMappedPaths that populates MappedPaths metadata on SourceRoot items is available. --> <PropertyGroup> <SourceRootMappedPathsFeatureSupported>true</SourceRootMappedPathsFeatureSupported> </PropertyGroup> <!-- If InitializeSourceControlInformation target isn't supported, we just continue without invoking that synchronization target. We'll proceed with SourceRoot (and other source control properties) provided by the user (or blank). --> <Target Name="_InitializeSourceRootMappedPathsFromSourceControl" DependsOnTargets="InitializeSourceControlInformation" Condition="'$(SourceControlInformationFeatureSupported)' == 'true'" /> <!-- ======= PathMap ======= If DeterministicSourcePaths is true sets PathMap based on SourceRoot.MappedPaths. This target requires SourceRoot to be initialized in order to calculate the PathMap. If SourceRoot doesn't contain any top-level roots an error is reported. --> <Target Name="_SetPathMapFromSourceRoots" DependsOnTargets="InitializeSourceRootMappedPaths" BeforeTargets="CoreCompile" Condition="'$(DeterministicSourcePaths)' == 'true'"> <ItemGroup> <_TopLevelSourceRoot Include="@(SourceRoot)" Condition="'%(SourceRoot.NestedRoot)' == ''"> <EscapedKey>$([MSBuild]::ValueOrDefault('%(Identity)', '').Replace(',', ',,').Replace('=', '=='))</EscapedKey> <EscapedValue>$([MSBuild]::ValueOrDefault('%(MappedPath)', '').Replace(',', ',,').Replace('=', '=='))</EscapedValue> </_TopLevelSourceRoot> </ItemGroup> <PropertyGroup Condition="'@(_TopLevelSourceRoot)' != ''"> <!-- Prepend the SourceRoot.MappedPath values to PathMap, if it already has a value. For each emitted source path the compiler applies the first mapping that matches the path. PathMap values set previously will thus only be applied if the mapping provided by SourceRoot.MappedPath doesn't match. Since SourceRoot.MappedPath is also used by SourceLink preferring it over manually set PathMap ensures that PathMap is consistent with SourceLink. --> <PathMap>@(_TopLevelSourceRoot->'%(EscapedKey)=%(EscapedValue)', ','),$(PathMap)</PathMap> </PropertyGroup> </Target> <!-- ======= CopyAdditionalFiles ======= If a user requests that any @(AdditionalFiles) items are copied to the output directory we add them to the @(None) group to ensure they will be copied. --> <Target Name="CopyAdditionalFiles" BeforeTargets="AssignTargetPaths"> <ItemGroup> <None Include="@(AdditionalFiles)" Condition="'%(AdditionalFiles.CopyToOutputDirectory)' != ''" /> </ItemGroup> </Target> <!-- ======================== CompilerGeneratedFilesOutputPath ======================== Controls output of generated files. CompilerGeneratedFilesOutputPath controls the location the files will be output to. The compiler will not emit any generated files when the path is empty, and defaults to a /generated directory in $(IntermediateOutputPath) if $(IntermediateOutputPath) has a value. EmitCompilerGeneratedFiles allows the user to control if anything is emitted by clearing the property when not true. When EmitCompilerGeneratedFiles is true, we ensure that CompilerGeneatedFilesOutputPath has a value and issue a warning if not. We will create CompilerGeneratedFilesOutputPath if it does not exist. --> <PropertyGroup> <EmitCompilerGeneratedFiles Condition="'$(EmitCompilerGeneratedFiles)' == ''">false</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath Condition="'$(EmitCompilerGeneratedFiles)' != 'true'"></CompilerGeneratedFilesOutputPath> <CompilerGeneratedFilesOutputPath Condition="'$(EmitCompilerGeneratedFiles)' == 'true' and '$(CompilerGeneratedFilesOutputPath)' == '' and '$(IntermediateOutputPath)' != ''">$(IntermediateOutputPath)/generated</CompilerGeneratedFilesOutputPath> </PropertyGroup> <Target Name="CreateCompilerGeneratedFilesOutputPath" BeforeTargets="CoreCompile" Condition="'$(EmitCompilerGeneratedFiles)' == 'true' and !('$(DesignTimeBuild)' == 'true' OR '$(BuildingProject)' != 'true')"> <Warning Condition="'$(CompilerGeneratedFilesOutputPath)' == ''" Text="EmitCompilerGeneratedFiles was true, but no CompilerGeneratedFilesOutputPath was provided. CompilerGeneratedFilesOutputPath must be set in order to emit generated files." /> <MakeDir Condition="'$(CompilerGeneratedFilesOutputPath)' != ''" Directories="$(CompilerGeneratedFilesOutputPath)" /> </Target> <!-- ======================== Component Debugger Support ======================== Add the specified VS capability if a user indicates this project supports component debugging --> <ItemGroup> <ProjectCapability Include="RoslynComponent" Condition="'$(IsRoslynComponent)' == 'true'"/> </ItemGroup> </Project>
1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/MSBuildTaskTests/Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.BuildTasks.UnitTests</RootNamespace> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>net5.0;net472</TargetFrameworks> <!-- Multiple test failures --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <Reference Include="Microsoft.Build.Engine" /> <Reference Include="System" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="Microsoft.Build" Version="$(MicrosoftBuildVersion)" /> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <ItemGroup> <Content Include="TestResources\**\*.*" /> <EmbeddedResource Include="TestResources\**\*.*" /> </ItemGroup> <PropertyGroup> <_DotNetSdkVersionFile>$(IntermediateOutputPath)\DotNetSdkVersion.g.cs</_DotNetSdkVersionFile> </PropertyGroup> <Target Name="_GenerateSdkVersionAttribute" BeforeTargets="CoreCompile" Outputs="$(_DotNetSdkVersionFile)"> <ItemGroup> <_Attribute Include="Microsoft.CodeAnalysis.BuildTasks.UnitTests.DotNetSdkVersionAttribute"> <_Parameter1>$(NETCoreSdkVersion)</_Parameter1> </_Attribute> </ItemGroup> <WriteCodeFragment AssemblyAttributes="@(_Attribute)" Language="$(Language)" OutputFile="$(_DotNetSdkVersionFile)"> <Output TaskParameter="OutputFile" ItemName="Compile" /> <Output TaskParameter="OutputFile" ItemName="FileWrites" /> </WriteCodeFragment> </Target> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.BuildTasks.UnitTests</RootNamespace> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>net5.0;net472</TargetFrameworks> <!-- Multiple test failures --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net472'"> <Reference Include="Microsoft.Build.Engine" /> <Reference Include="System" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="Microsoft.Build" Version="$(MicrosoftBuildVersion)" /> <PackageReference Include="Microsoft.Build.Framework" Version="$(MicrosoftBuildFrameworkVersion)" /> <PackageReference Include="Microsoft.Build.Tasks.Core" Version="$(MicrosoftBuildTasksCoreVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <ItemGroup> <Content Include="TestResources\**\*.*" /> <EmbeddedResource Include="TestResources\**\*.*" /> </ItemGroup> <PropertyGroup> <_DotNetSdkVersionFile>$(IntermediateOutputPath)\DotNetVersions.g.cs</_DotNetSdkVersionFile> </PropertyGroup> <Target Name="_GenerateSdkVersionAttribute" BeforeTargets="CoreCompile" Outputs="$(_DotNetSdkVersionFile)"> <ItemGroup> <_Attribute Include="Microsoft.CodeAnalysis.BuildTasks.UnitTests.DotNetSdkVersionAttribute"> <_Parameter1>$(NETCoreSdkVersion)</_Parameter1> </_Attribute> <_Attribute Include="System.Reflection.AssemblyMetadataAttribute"> <_Parameter1>CurrentCompilerApiVersion</_Parameter1> <_Parameter2>$([System.Version]::Parse($(VersionPrefix)).Major).$([System.Version]::Parse($(VersionPrefix)).Minor)</_Parameter2> </_Attribute> </ItemGroup> <WriteCodeFragment AssemblyAttributes="@(_Attribute)" Language="$(Language)" OutputFile="$(_DotNetSdkVersionFile)"> <Output TaskParameter="OutputFile" ItemName="Compile" /> <Output TaskParameter="OutputFile" ItemName="FileWrites" /> </WriteCodeFragment> </Target> </Project>
1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/MSBuildTaskTests/TargetTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // uncomment the below define to dump binlogs of each test //#define DUMP_MSBUILD_BIN_LOG using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using Roslyn.Test.Utilities; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public class TargetTests : TestBase { [Fact] public void GenerateEditorConfigShouldNotRunWhenNoPropertiesOrMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenMetadataRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleItemMetadata Include=""item"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesAndMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCanBeDisabled() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <GenerateMSBuildEditorConfigFile>false</GenerateMSBuildEditorConfigFile> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCoreEvaluatesProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <ValueToGet>abc</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("abc", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <RealValue>def</RealValue> <ValueToGet>$(RealValue)</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("def", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""abc"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <DynamicValue>abc</DynamicValue> </PropertyGroup> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""$(DynamicValue)"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> <CompilerVisibleItemMetadata Include=""Compile2"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMalformedCompilerVisibleItemMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("", metaName.EvaluatedValue); } [Theory] [InlineData(".NETFramework", "4.5", "7.3")] [InlineData(".NETFramework", "4.7.2", "7.3")] [InlineData(".NETFramework", "4.8", "7.3")] [InlineData(".NETCoreApp", "1.0", "7.3")] [InlineData(".NETCoreApp", "2.0", "7.3")] [InlineData(".NETCoreApp", "2.1", "7.3")] [InlineData(".NETCoreApp", "3.0", "8.0")] [InlineData(".NETCoreApp", "3.1", "8.0")] [InlineData(".NETCoreApp", "5.0", "9.0")] [InlineData(".NETCoreApp", "6.0", "10.0")] [InlineData(".NETCoreApp", "7.0", "")] [InlineData(".NETStandard", "1.0", "7.3")] [InlineData(".NETStandard", "1.5", "7.3")] [InlineData(".NETStandard", "2.0", "7.3")] [InlineData(".NETStandard", "2.1", "8.0")] [InlineData("UnknownTFM", "0.0", "7.3")] [InlineData("UnknownTFM", "5.0", "7.3")] [InlineData("UnknownTFM", "6.0", "7.3")] public void LanguageVersionGivenTargetFramework(string tfi, string tfv, string expectedVersion) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>{tfi}</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>{tfv}</_TargetFrameworkVersionWithoutV> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal(expectedVersion, langVersion); Assert.Equal(expectedVersion, maxLangVersion); // This will fail whenever the current language version is updated. // Ensure you update the target files to select the correct CSharp version for the newest target framework // and add to the theory data above to cover it, before changing this version to make the test pass again. Assert.Equal(CSharp.LanguageVersion.CSharp10, CSharp.LanguageVersionFacts.CurrentVersion); } [Fact] public void ExplicitLangVersion() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>55.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal("55.0", langVersion); Assert.Equal("7.3", maxLangVersion); } [Fact] public void MaxSupportedLangVersionIsReadable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void MaxSupportedLangVersionIsnotWriteable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> <MaxSupportedLangVersion>9.0</MaxSupportedLangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void GenerateEditorConfigIsPassedToTheCompiler() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("EditorConfigFiles"); Assert.Single(items); } [Fact] public void AdditionalFilesAreAddedToNoneWhenCopied() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <AdditionalFiles Include=""file1.cs"" CopyToOutputDirectory=""Always"" /> <AdditionalFiles Include=""file2.cs"" CopyToOutputDirectory=""PreserveNewest"" /> <AdditionalFiles Include=""file3.cs"" CopyToOutputDirectory=""Never"" /> <AdditionalFiles Include=""file4.cs"" CopyToOutputDirectory="""" /> <AdditionalFiles Include=""file5.cs"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CopyAdditionalFiles", GetTestLoggers()); Assert.True(runSuccess); var noneItems = instance.GetItems("None").ToArray(); Assert.Equal(3, noneItems.Length); Assert.Equal("file1.cs", noneItems[0].EvaluatedInclude); Assert.Equal("Always", noneItems[0].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file2.cs", noneItems[1].EvaluatedInclude); Assert.Equal("PreserveNewest", noneItems[1].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file3.cs", noneItems[2].EvaluatedInclude); Assert.Equal("Never", noneItems[2].GetMetadataValue("CopyToOutputDirectory")); } [Fact] public void GeneratedFilesOutputPathHasDefaults() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Fact] public void GeneratedFilesOutputPathDefaultsToIntermediateOutputPathWhenSet() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("true", emit); Assert.Equal("fallbackDirectory/generated", dir); } [Fact] public void GeneratedFilesOutputPathDefaultsIsEmptyWhenEmitDisable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Theory] [InlineData(true, "generatedDirectory")] [InlineData(true, null)] [InlineData(false, "generatedDirectory")] [InlineData(false, null)] public void GeneratedFilesOutputPathCanBeSetAndSuppressed(bool emitGeneratedFiles, string? generatedFilesDir) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>{(emitGeneratedFiles.ToString().ToLower())}</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>{generatedFilesDir}</CompilerGeneratedFilesOutputPath> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal(emitGeneratedFiles.ToString().ToLower(), emit); if (emitGeneratedFiles) { string expectedDir = generatedFilesDir ?? "fallbackDirectory/generated"; Assert.Equal(expectedDir, dir); } else { Assert.Equal(string.Empty, dir); } } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? runAnalyzersDuringBuild) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var runAnalyzersDuringBuildPropertyGroupString = getPropertyGroup("RunAnalyzersDuringBuild", runAnalyzersDuringBuild); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {runAnalyzersDuringBuildPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); // Verify "RunAnalyzers" overrides "RunAnalyzersDuringBuild". // If neither properties are set, analyzers are enabled by default. var analyzersEnabled = runAnalyzers ?? runAnalyzersDuringBuild ?? true; var expectedSkipAnalyzersValue = !analyzersEnabled ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestImplicitlySkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? implicitBuild, [CombinatorialValues(true, false, null)] bool? treatWarningsAsErrors, [CombinatorialValues(true, false, null)] bool? optimizeImplicitBuild, [CombinatorialValues(true, null)] bool? sdkStyleProject) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var implicitBuildPropertyGroupString = getPropertyGroup("IsImplicitlyTriggeredBuild", implicitBuild); var treatWarningsAsErrorsPropertyGroupString = getPropertyGroup("TreatWarningsAsErrors", treatWarningsAsErrors); var optimizeImplicitBuildPropertyGroupString = getPropertyGroup("OptimizeImplicitlyTriggeredBuild", optimizeImplicitBuild); var sdkStyleProjectPropertyGroupString = getPropertyGroup("UsingMicrosoftNETSdk", sdkStyleProject); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {implicitBuildPropertyGroupString} {treatWarningsAsErrorsPropertyGroupString} {optimizeImplicitBuildPropertyGroupString} {sdkStyleProjectPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var analyzersEnabled = runAnalyzers ?? true; var expectedImplicitlySkippedAnalyzers = analyzersEnabled && implicitBuild == true && sdkStyleProject == true && (treatWarningsAsErrors != true || optimizeImplicitBuild == true); var expectedImplicitlySkippedAnalyzersValue = expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualImplicitlySkippedAnalyzersValue = instance.GetPropertyValue("_ImplicitlySkipAnalyzers"); Assert.Equal(expectedImplicitlySkippedAnalyzersValue, actualImplicitlySkippedAnalyzersValue); var expectedSkipAnalyzersValue = !analyzersEnabled || expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); var expectedFeaturesValue = expectedImplicitlySkippedAnalyzers ? "run-nullable-analysis=never;" : ""; var actualFeaturesValue = instance.GetPropertyValue("Features"); Assert.Equal(expectedFeaturesValue, actualFeaturesValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestLastBuildWithSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, bool lastBuildWithSkipAnalyzersFileExists) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var intermediatePathDir = Temp.CreateDirectory(); var intermediatePath = intermediatePathDir + Path.DirectorySeparatorChar.ToString(); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} <PropertyGroup> <IntermediateOutputPath>{intermediatePath}</IntermediateOutputPath> </PropertyGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); var msbuildProjectFileName = instance.GetPropertyValue("MSBuildProjectFile"); var expectedLastBuildWithSkipAnalyzers = intermediatePath + msbuildProjectFileName + ".BuildWithSkipAnalyzers"; if (lastBuildWithSkipAnalyzersFileExists) { _ = intermediatePathDir.CreateFile(msbuildProjectFileName + ".BuildWithSkipAnalyzers"); } bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var actualLastBuildWithSkipAnalyzers = instance.GetPropertyValue("_LastBuildWithSkipAnalyzers"); Assert.Equal(expectedLastBuildWithSkipAnalyzers, actualLastBuildWithSkipAnalyzers); var skipAnalyzers = !(runAnalyzers ?? true); var expectedCustomAdditionalCompileInput = lastBuildWithSkipAnalyzersFileExists && !skipAnalyzers; var items = instance.GetItems("CustomAdditionalCompileInputs"); var expectedItemCount = expectedCustomAdditionalCompileInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedCustomAdditionalCompileInput) { Assert.Equal(expectedLastBuildWithSkipAnalyzers, items.Single().EvaluatedInclude); } var expectedUpToDateCheckInput = lastBuildWithSkipAnalyzersFileExists; items = instance.GetItems("UpToDateCheckInput"); expectedItemCount = expectedUpToDateCheckInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedUpToDateCheckInput) { var item = items.Single(); Assert.Equal(expectedLastBuildWithSkipAnalyzers, item.EvaluatedInclude); Assert.Equal("ImplicitBuild", item.GetMetadataValue("Kind")); } return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Fact] public void ProjectCapabilityIsNotAddedWhenRoslynComponentIsUnspecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.DoesNotContain("RoslynComponent", caps); } [Fact] public void ProjectCapabilityIsAddedWhenRoslynComponentSpecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IsRoslynComponent>true</IsRoslynComponent> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.Contains("RoslynComponent", caps); } private static ProjectInstance CreateProjectInstance(XmlReader reader) { Project proj = new Project(reader); // add a dummy prepare for build target proj.Xml.AddTarget("PrepareForBuild"); // create a dummy WriteLinesToFile task addTask(proj, "WriteLinesToFile", new() { { "Lines", "System.String[]" }, { "File", "System.String" }, { "Overwrite", "System.Boolean" }, { "WriteOnlyWhenDifferent", "System.Boolean" } }); // dummy makeDir task addTask(proj, "MakeDir", new() { { "Directories", "System.String[]" } }); // dummy Message task addTask(proj, "Message", new() { { "Text", "System.String" }, { "Importance", "System.String" } }); // create an instance and return it return proj.CreateProjectInstance(); static void addTask(Project proj, string taskName, Dictionary<string, string> parameters) { var task = proj.Xml.AddUsingTask(taskName, string.Empty, Assembly.GetExecutingAssembly().FullName); task.TaskFactory = nameof(DummyTaskFactory); var taskParams = task.AddParameterGroup(); foreach (var kvp in parameters) { taskParams.AddParameter(kvp.Key, string.Empty, string.Empty, kvp.Value); } } } private static ILogger[] GetTestLoggers([CallerMemberName] string callerName = "") { #if DUMP_MSBUILD_BIN_LOG return new ILogger[] { new Build.Logging.BinaryLogger() { Parameters = callerName + ".binlog" } }; #else return Array.Empty<ILogger>(); #endif } } /// <summary> /// Task factory that creates empty tasks for testing /// </summary> /// <remarks> /// Replace any task with a dummy task by adding a <c>UsingTask</c> /// <code> /// <UsingTask TaskName="[TaskToReplace]" TaskFactory="DummyTaskFactory"> /// <ParameterGroup> /// <Param1 ParameterType="[Type]" /> /// </ParameterGroup> /// </UsingTask> /// </code> /// /// You can specify the parameters the task should have via a <c>ParameterGroup</c> /// These should match the task you are replacing. /// </remarks> public sealed class DummyTaskFactory : ITaskFactory { public string FactoryName { get => "DummyTaskFactory"; } public Type TaskType { get => typeof(DummyTaskFactory); } private TaskPropertyInfo[]? _props; public void CleanupTask(ITask task) { } public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new DummyTask(); public TaskPropertyInfo[]? GetTaskParameters() => _props; public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { _props = parameterGroup.Values.ToArray(); return true; } private class DummyTask : IGeneratedTask { public IBuildEngine? BuildEngine { get; set; } public ITaskHost? HostObject { get; set; } public bool Execute() => true; public object GetPropertyValue(TaskPropertyInfo property) => null!; public void SetPropertyValue(TaskPropertyInfo property, object 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. // uncomment the below define to dump binlogs of each test //#define DUMP_MSBUILD_BIN_LOG using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using Roslyn.Test.Utilities; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public class TargetTests : TestBase { [Fact] public void GenerateEditorConfigShouldNotRunWhenNoPropertiesOrMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenMetadataRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleItemMetadata Include=""item"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesAndMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCanBeDisabled() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <GenerateMSBuildEditorConfigFile>false</GenerateMSBuildEditorConfigFile> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCoreEvaluatesProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <ValueToGet>abc</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("abc", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <RealValue>def</RealValue> <ValueToGet>$(RealValue)</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("def", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""abc"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <DynamicValue>abc</DynamicValue> </PropertyGroup> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""$(DynamicValue)"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> <CompilerVisibleItemMetadata Include=""Compile2"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMalformedCompilerVisibleItemMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("", metaName.EvaluatedValue); } [Theory] [InlineData(".NETFramework", "4.5", "7.3")] [InlineData(".NETFramework", "4.7.2", "7.3")] [InlineData(".NETFramework", "4.8", "7.3")] [InlineData(".NETCoreApp", "1.0", "7.3")] [InlineData(".NETCoreApp", "2.0", "7.3")] [InlineData(".NETCoreApp", "2.1", "7.3")] [InlineData(".NETCoreApp", "3.0", "8.0")] [InlineData(".NETCoreApp", "3.1", "8.0")] [InlineData(".NETCoreApp", "5.0", "9.0")] [InlineData(".NETCoreApp", "6.0", "10.0")] [InlineData(".NETCoreApp", "7.0", "")] [InlineData(".NETStandard", "1.0", "7.3")] [InlineData(".NETStandard", "1.5", "7.3")] [InlineData(".NETStandard", "2.0", "7.3")] [InlineData(".NETStandard", "2.1", "8.0")] [InlineData("UnknownTFM", "0.0", "7.3")] [InlineData("UnknownTFM", "5.0", "7.3")] [InlineData("UnknownTFM", "6.0", "7.3")] public void LanguageVersionGivenTargetFramework(string tfi, string tfv, string expectedVersion) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>{tfi}</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>{tfv}</_TargetFrameworkVersionWithoutV> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal(expectedVersion, langVersion); Assert.Equal(expectedVersion, maxLangVersion); // This will fail whenever the current language version is updated. // Ensure you update the target files to select the correct CSharp version for the newest target framework // and add to the theory data above to cover it, before changing this version to make the test pass again. Assert.Equal(CSharp.LanguageVersion.CSharp10, CSharp.LanguageVersionFacts.CurrentVersion); } [Fact] public void ExplicitLangVersion() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>55.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal("55.0", langVersion); Assert.Equal("7.3", maxLangVersion); } [Fact] public void MaxSupportedLangVersionIsReadable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void MaxSupportedLangVersionIsnotWriteable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> <MaxSupportedLangVersion>9.0</MaxSupportedLangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void GenerateEditorConfigIsPassedToTheCompiler() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("EditorConfigFiles"); Assert.Single(items); } [Fact] public void AdditionalFilesAreAddedToNoneWhenCopied() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <AdditionalFiles Include=""file1.cs"" CopyToOutputDirectory=""Always"" /> <AdditionalFiles Include=""file2.cs"" CopyToOutputDirectory=""PreserveNewest"" /> <AdditionalFiles Include=""file3.cs"" CopyToOutputDirectory=""Never"" /> <AdditionalFiles Include=""file4.cs"" CopyToOutputDirectory="""" /> <AdditionalFiles Include=""file5.cs"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CopyAdditionalFiles", GetTestLoggers()); Assert.True(runSuccess); var noneItems = instance.GetItems("None").ToArray(); Assert.Equal(3, noneItems.Length); Assert.Equal("file1.cs", noneItems[0].EvaluatedInclude); Assert.Equal("Always", noneItems[0].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file2.cs", noneItems[1].EvaluatedInclude); Assert.Equal("PreserveNewest", noneItems[1].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file3.cs", noneItems[2].EvaluatedInclude); Assert.Equal("Never", noneItems[2].GetMetadataValue("CopyToOutputDirectory")); } [Fact] public void GeneratedFilesOutputPathHasDefaults() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Fact] public void GeneratedFilesOutputPathDefaultsToIntermediateOutputPathWhenSet() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("true", emit); Assert.Equal("fallbackDirectory/generated", dir); } [Fact] public void GeneratedFilesOutputPathDefaultsIsEmptyWhenEmitDisable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Theory] [InlineData(true, "generatedDirectory")] [InlineData(true, null)] [InlineData(false, "generatedDirectory")] [InlineData(false, null)] public void GeneratedFilesOutputPathCanBeSetAndSuppressed(bool emitGeneratedFiles, string? generatedFilesDir) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>{(emitGeneratedFiles.ToString().ToLower())}</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>{generatedFilesDir}</CompilerGeneratedFilesOutputPath> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal(emitGeneratedFiles.ToString().ToLower(), emit); if (emitGeneratedFiles) { string expectedDir = generatedFilesDir ?? "fallbackDirectory/generated"; Assert.Equal(expectedDir, dir); } else { Assert.Equal(string.Empty, dir); } } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? runAnalyzersDuringBuild) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var runAnalyzersDuringBuildPropertyGroupString = getPropertyGroup("RunAnalyzersDuringBuild", runAnalyzersDuringBuild); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {runAnalyzersDuringBuildPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); // Verify "RunAnalyzers" overrides "RunAnalyzersDuringBuild". // If neither properties are set, analyzers are enabled by default. var analyzersEnabled = runAnalyzers ?? runAnalyzersDuringBuild ?? true; var expectedSkipAnalyzersValue = !analyzersEnabled ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestImplicitlySkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? implicitBuild, [CombinatorialValues(true, false, null)] bool? treatWarningsAsErrors, [CombinatorialValues(true, false, null)] bool? optimizeImplicitBuild, [CombinatorialValues(true, null)] bool? sdkStyleProject) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var implicitBuildPropertyGroupString = getPropertyGroup("IsImplicitlyTriggeredBuild", implicitBuild); var treatWarningsAsErrorsPropertyGroupString = getPropertyGroup("TreatWarningsAsErrors", treatWarningsAsErrors); var optimizeImplicitBuildPropertyGroupString = getPropertyGroup("OptimizeImplicitlyTriggeredBuild", optimizeImplicitBuild); var sdkStyleProjectPropertyGroupString = getPropertyGroup("UsingMicrosoftNETSdk", sdkStyleProject); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {implicitBuildPropertyGroupString} {treatWarningsAsErrorsPropertyGroupString} {optimizeImplicitBuildPropertyGroupString} {sdkStyleProjectPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var analyzersEnabled = runAnalyzers ?? true; var expectedImplicitlySkippedAnalyzers = analyzersEnabled && implicitBuild == true && sdkStyleProject == true && (treatWarningsAsErrors != true || optimizeImplicitBuild == true); var expectedImplicitlySkippedAnalyzersValue = expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualImplicitlySkippedAnalyzersValue = instance.GetPropertyValue("_ImplicitlySkipAnalyzers"); Assert.Equal(expectedImplicitlySkippedAnalyzersValue, actualImplicitlySkippedAnalyzersValue); var expectedSkipAnalyzersValue = !analyzersEnabled || expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); var expectedFeaturesValue = expectedImplicitlySkippedAnalyzers ? "run-nullable-analysis=never;" : ""; var actualFeaturesValue = instance.GetPropertyValue("Features"); Assert.Equal(expectedFeaturesValue, actualFeaturesValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestLastBuildWithSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, bool lastBuildWithSkipAnalyzersFileExists) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var intermediatePathDir = Temp.CreateDirectory(); var intermediatePath = intermediatePathDir + Path.DirectorySeparatorChar.ToString(); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} <PropertyGroup> <IntermediateOutputPath>{intermediatePath}</IntermediateOutputPath> </PropertyGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); var msbuildProjectFileName = instance.GetPropertyValue("MSBuildProjectFile"); var expectedLastBuildWithSkipAnalyzers = intermediatePath + msbuildProjectFileName + ".BuildWithSkipAnalyzers"; if (lastBuildWithSkipAnalyzersFileExists) { _ = intermediatePathDir.CreateFile(msbuildProjectFileName + ".BuildWithSkipAnalyzers"); } bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var actualLastBuildWithSkipAnalyzers = instance.GetPropertyValue("_LastBuildWithSkipAnalyzers"); Assert.Equal(expectedLastBuildWithSkipAnalyzers, actualLastBuildWithSkipAnalyzers); var skipAnalyzers = !(runAnalyzers ?? true); var expectedCustomAdditionalCompileInput = lastBuildWithSkipAnalyzersFileExists && !skipAnalyzers; var items = instance.GetItems("CustomAdditionalCompileInputs"); var expectedItemCount = expectedCustomAdditionalCompileInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedCustomAdditionalCompileInput) { Assert.Equal(expectedLastBuildWithSkipAnalyzers, items.Single().EvaluatedInclude); } var expectedUpToDateCheckInput = lastBuildWithSkipAnalyzersFileExists; items = instance.GetItems("UpToDateCheckInput"); expectedItemCount = expectedUpToDateCheckInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedUpToDateCheckInput) { var item = items.Single(); Assert.Equal(expectedLastBuildWithSkipAnalyzers, item.EvaluatedInclude); Assert.Equal("ImplicitBuild", item.GetMetadataValue("Kind")); } return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Fact] public void ProjectCapabilityIsNotAddedWhenRoslynComponentIsUnspecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.DoesNotContain("RoslynComponent", caps); } [Fact] public void ProjectCapabilityIsAddedWhenRoslynComponentSpecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IsRoslynComponent>true</IsRoslynComponent> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.Contains("RoslynComponent", caps); } [Fact] public void CompilerApiVersionIsSet() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var compilerApiVersionString = instance.GetPropertyValue("CompilerApiVersion"); Assert.StartsWith("roslyn", compilerApiVersionString); var compilerApiVersion = Version.Parse(compilerApiVersionString.Substring("roslyn".Length)); var expectedVersionString = GetType().Assembly.GetCustomAttributes<AssemblyMetadataAttribute>() .Single(a => a.Key == "CurrentCompilerApiVersion") .Value ?? string.Empty; var expectedVersion = Version.Parse(expectedVersionString); Assert.Equal(expectedVersion, compilerApiVersion); } private static ProjectInstance CreateProjectInstance(XmlReader reader) { Project proj = new Project(reader); // add a dummy prepare for build target proj.Xml.AddTarget("PrepareForBuild"); // create a dummy WriteLinesToFile task addTask(proj, "WriteLinesToFile", new() { { "Lines", "System.String[]" }, { "File", "System.String" }, { "Overwrite", "System.Boolean" }, { "WriteOnlyWhenDifferent", "System.Boolean" } }); // dummy makeDir task addTask(proj, "MakeDir", new() { { "Directories", "System.String[]" } }); // dummy Message task addTask(proj, "Message", new() { { "Text", "System.String" }, { "Importance", "System.String" } }); // create an instance and return it return proj.CreateProjectInstance(); static void addTask(Project proj, string taskName, Dictionary<string, string> parameters) { var task = proj.Xml.AddUsingTask(taskName, string.Empty, Assembly.GetExecutingAssembly().FullName); task.TaskFactory = nameof(DummyTaskFactory); var taskParams = task.AddParameterGroup(); foreach (var kvp in parameters) { taskParams.AddParameter(kvp.Key, string.Empty, string.Empty, kvp.Value); } } } private static ILogger[] GetTestLoggers([CallerMemberName] string callerName = "") { #if DUMP_MSBUILD_BIN_LOG return new ILogger[] { new Build.Logging.BinaryLogger() { Parameters = callerName + ".binlog" } }; #else return Array.Empty<ILogger>(); #endif } } /// <summary> /// Task factory that creates empty tasks for testing /// </summary> /// <remarks> /// Replace any task with a dummy task by adding a <c>UsingTask</c> /// <code> /// <UsingTask TaskName="[TaskToReplace]" TaskFactory="DummyTaskFactory"> /// <ParameterGroup> /// <Param1 ParameterType="[Type]" /> /// </ParameterGroup> /// </UsingTask> /// </code> /// /// You can specify the parameters the task should have via a <c>ParameterGroup</c> /// These should match the task you are replacing. /// </remarks> public sealed class DummyTaskFactory : ITaskFactory { public string FactoryName { get => "DummyTaskFactory"; } public Type TaskType { get => typeof(DummyTaskFactory); } private TaskPropertyInfo[]? _props; public void CleanupTask(ITask task) { } public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new DummyTask(); public TaskPropertyInfo[]? GetTaskParameters() => _props; public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { _props = parameterGroup.Values.ToArray(); return true; } private class DummyTask : IGeneratedTask { public IBuildEngine? BuildEngine { get; set; } public ITaskHost? HostObject { get; set; } public bool Execute() => true; public object GetPropertyValue(TaskPropertyInfo property) => null!; public void SetPropertyValue(TaskPropertyInfo property, object value) { } } } }
1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/NuGet/Microsoft.Net.Compilers.Toolset/DesktopCompilerArtifacts.targets
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <!-- The CompilerArtifact list is used to generate Microsoft.Net.Compilers package, VS.Toolset.Roslyn CoreXT package and Microsoft.CodeAnalysis.Compilers Willow VSIX. Keeping the list in central location allows us to make sure that these packages include the same files. Ngen* attributes indicate how VS should NGEN the assemblies that are distributed by VS Setup. NgenApplication is relative to the Roslyn install directory within MSBuild (i.e. MSBuild\15.0\Bin\Roslyn). Assemblies NGEN'd as priority 1 are selected based on how much JIT time they contribute, when not NGEN'd, to the Visual Studio scenarios listed below. The more JIT time required for an assembly, the more likely there will be a noticeable performance impact. 1. Start the IDE. 2. Load a managed solution. 3. Build the solution. Set OverwriteOptimizationData to true to replace optimization data already embedded in the assembly with data retrieved from VS training scenarios. We only need to specify this for assemblies built outside or Roslyn repo since the projects in Roslyn repo are responsible for embedding VS training data to the assemblies they produce. --> <Target Name="InitializeDesktopCompilerArtifacts"> <ItemGroup> <!-- The Roslyn built binaries must be taken from these locations because this is the location where signing occurs --> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.dll" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.CSharp.dll" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.Scripting\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.Scripting.dll" NgenArchitecture="all" NgenApplication="csi.exe"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.Scripting\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.CSharp.Scripting.dll" NgenArchitecture="all" NgenApplication="csi.exe"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.VisualBasic.dll" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\Microsoft.DiaSymReader.Native.amd64.dll" Condition="'$(DotNetBuildFromSource)' != 'true'"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\Microsoft.DiaSymReader.Native.x86.dll" Condition="'$(DotNetBuildFromSource)' != 'true'"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\csc.exe" NgenArchitecture="all" NgenApplication="csc.exe" NgenPriority="2"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\csc.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\csc.rsp"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\csi.exe" NgenArchitecture="all" NgenApplication="csi.exe" NgenPriority="2"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\csi.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\csi.rsp"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)vbc\$(Configuration)\net472\vbc.exe" NgenArchitecture="all" NgenApplication="vbc.exe" NgenPriority="2"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)vbc\$(Configuration)\net472\vbc.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)vbc\$(Configuration)\net472\vbc.rsp"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)VBCSCompiler\$(Configuration)\net472\VBCSCompiler.exe" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)VBCSCompiler\$(Configuration)\net472\VBCSCompiler.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.Build.Tasks.CodeAnalysis.dll" NgenArchitecture="all" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.Managed.Core.targets"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.CSharp.Core.targets"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.VisualBasic.Core.targets"/> <!-- Do not overwrite optimization data of System.Threading.Tasks.Extensions.dll This assembly is signed by Open key in CoreFX and MicroBuild does not support this key. Arcade SignTool doesn't support signing directly at this point either. https://github.com/dotnet/arcade/issues/1204 We don't currently collect optimization data for the following assemblies. --> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Threading.Tasks.Extensions.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Buffers.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Memory.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Numerics.Vectors.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Text.Encoding.CodePages.dll"/> <!-- System.Numerics.Vector requires JIT, since its size is dynamic and based on the underlying CPU support. --> <_NoNGen Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Numerics.Vectors.dll"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.*.dll" Exclude="@(_NoOptimizationData)" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" OverwriteNgenOptimizationData="true"/> <!-- Note: do not use Update attribute (see https://github.com/microsoft/msbuild/issues/1124) --> <DesktopCompilerArtifact NgenPriority="1" Condition="'%(Identity)' == '$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Collections.Immutable.dll'" /> <DesktopCompilerArtifact NgenPriority="1" Condition="'%(Identity)' == '$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Reflection.Metadata.dll'" /> <DesktopCompilerArtifact Include="@(_NoOptimizationData)" Exclude="@(_NoNGen)" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" OverwriteNgenOptimizationData="false"/> <DesktopCompilerArtifact Include="@(_NoNGen)" /> <!-- Satellite assemblies --> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.CSharp.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.Scripting\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.Scripting.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.Scripting\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.CSharp.Scripting.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.VisualBasic.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\**\Microsoft.Build.Tasks.CodeAnalysis.resources.dll" /> </ItemGroup> </Target> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <!-- The CompilerArtifact list is used to generate Microsoft.Net.Compilers package, VS.Toolset.Roslyn CoreXT package and Microsoft.CodeAnalysis.Compilers Willow VSIX. Keeping the list in central location allows us to make sure that these packages include the same files. Ngen* attributes indicate how VS should NGEN the assemblies that are distributed by VS Setup. NgenApplication is relative to the Roslyn install directory within MSBuild (i.e. MSBuild\15.0\Bin\Roslyn). Assemblies NGEN'd as priority 1 are selected based on how much JIT time they contribute, when not NGEN'd, to the Visual Studio scenarios listed below. The more JIT time required for an assembly, the more likely there will be a noticeable performance impact. 1. Start the IDE. 2. Load a managed solution. 3. Build the solution. Set OverwriteOptimizationData to true to replace optimization data already embedded in the assembly with data retrieved from VS training scenarios. We only need to specify this for assemblies built outside or Roslyn repo since the projects in Roslyn repo are responsible for embedding VS training data to the assemblies they produce. --> <Target Name="InitializeDesktopCompilerArtifacts"> <ItemGroup> <!-- The Roslyn built binaries must be taken from these locations because this is the location where signing occurs --> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.dll" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.CSharp.dll" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.Scripting\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.Scripting.dll" NgenArchitecture="all" NgenApplication="csi.exe"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.Scripting\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.CSharp.Scripting.dll" NgenArchitecture="all" NgenApplication="csi.exe"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic\$(Configuration)\netstandard2.0\Microsoft.CodeAnalysis.VisualBasic.dll" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\Microsoft.DiaSymReader.Native.amd64.dll" Condition="'$(DotNetBuildFromSource)' != 'true'"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\Microsoft.DiaSymReader.Native.x86.dll" Condition="'$(DotNetBuildFromSource)' != 'true'"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\csc.exe" NgenArchitecture="all" NgenApplication="csc.exe" NgenPriority="2"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\csc.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csc\$(Configuration)\net472\csc.rsp"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\csi.exe" NgenArchitecture="all" NgenApplication="csi.exe" NgenPriority="2"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\csi.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\csi.rsp"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)vbc\$(Configuration)\net472\vbc.exe" NgenArchitecture="all" NgenApplication="vbc.exe" NgenPriority="2"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)vbc\$(Configuration)\net472\vbc.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)vbc\$(Configuration)\net472\vbc.rsp"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)VBCSCompiler\$(Configuration)\net472\VBCSCompiler.exe" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)VBCSCompiler\$(Configuration)\net472\VBCSCompiler.exe.config"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.Build.Tasks.CodeAnalysis.dll" NgenArchitecture="all" NgenPriority="1"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.Managed.Core.CurrentVersions.targets"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.Managed.Core.targets"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.CSharp.Core.targets"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\Microsoft.VisualBasic.Core.targets"/> <!-- Do not overwrite optimization data of System.Threading.Tasks.Extensions.dll This assembly is signed by Open key in CoreFX and MicroBuild does not support this key. Arcade SignTool doesn't support signing directly at this point either. https://github.com/dotnet/arcade/issues/1204 We don't currently collect optimization data for the following assemblies. --> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Threading.Tasks.Extensions.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Buffers.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Memory.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Numerics.Vectors.dll"/> <_NoOptimizationData Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Text.Encoding.CodePages.dll"/> <!-- System.Numerics.Vector requires JIT, since its size is dynamic and based on the underlying CPU support. --> <_NoNGen Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Numerics.Vectors.dll"/> <DesktopCompilerArtifact Include="$(ArtifactsBinDir)csi\$(Configuration)\net472\System.*.dll" Exclude="@(_NoOptimizationData)" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" OverwriteNgenOptimizationData="true"/> <!-- Note: do not use Update attribute (see https://github.com/microsoft/msbuild/issues/1124) --> <DesktopCompilerArtifact NgenPriority="1" Condition="'%(Identity)' == '$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Collections.Immutable.dll'" /> <DesktopCompilerArtifact NgenPriority="1" Condition="'%(Identity)' == '$(ArtifactsBinDir)csi\$(Configuration)\net472\System.Reflection.Metadata.dll'" /> <DesktopCompilerArtifact Include="@(_NoOptimizationData)" Exclude="@(_NoNGen)" NgenArchitecture="all" NgenApplication="VBCSCompiler.exe" OverwriteNgenOptimizationData="false"/> <DesktopCompilerArtifact Include="@(_NoNGen)" /> <!-- Satellite assemblies --> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.CSharp.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.Scripting\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.Scripting.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.Scripting\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.CSharp.Scripting.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic\$(Configuration)\netstandard2.0\**\Microsoft.CodeAnalysis.VisualBasic.resources.dll" /> <DesktopCompilerResourceArtifact Include="$(ArtifactsBinDir)Microsoft.Build.Tasks.CodeAnalysis\$(Configuration)\net472\**\Microsoft.Build.Tasks.CodeAnalysis.resources.dll" /> </ItemGroup> </Target> </Project>
1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/CSharp/Portable/Organizing/Organizers/IndexerDeclarationOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer<IndexerDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IndexerDeclarationOrganizer() { } protected override IndexerDeclarationSyntax Organize( IndexerDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( attributeLists: syntax.AttributeLists, modifiers: ModifiersOrganizer.Organize(syntax.Modifiers), type: syntax.Type, explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier, thisKeyword: syntax.ThisKeyword, parameterList: syntax.ParameterList, accessorList: syntax.AccessorList, expressionBody: syntax.ExpressionBody, semicolonToken: syntax.SemicolonToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class IndexerDeclarationOrganizer : AbstractSyntaxNodeOrganizer<IndexerDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IndexerDeclarationOrganizer() { } protected override IndexerDeclarationSyntax Organize( IndexerDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update( attributeLists: syntax.AttributeLists, modifiers: ModifiersOrganizer.Organize(syntax.Modifiers), type: syntax.Type, explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier, thisKeyword: syntax.ThisKeyword, parameterList: syntax.ParameterList, accessorList: syntax.AccessorList, expressionBody: syntax.ExpressionBody, semicolonToken: syntax.SemicolonToken); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.CallbackDispatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolFinderService)), Shared] internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolFinderService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallbackDispatcher() { } private FindLiteralsServerCallback GetFindLiteralsCallback(RemoteServiceCallbackId callbackId) => (FindLiteralsServerCallback)GetCallback(callbackId); private FindReferencesServerCallback GetFindReferencesCallback(RemoteServiceCallbackId callbackId) => (FindReferencesServerCallback)GetCallback(callbackId); // references public ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnCompletedAsync(cancellationToken); public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnDefinitionFoundAsync(symbolGroup, cancellationToken); public ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnFindInDocumentCompletedAsync(documentId, cancellationToken); public ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnFindInDocumentStartedAsync(documentId, cancellationToken); public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnReferenceFoundAsync(symbolGroup, definition, reference, cancellationToken); public ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnStartedAsync(cancellationToken); // literals public ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetFindLiteralsCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindLiteralsCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken) => GetFindLiteralsCallback(callbackId).OnLiteralReferenceFoundAsync(documentId, span, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteSymbolFinderService)), Shared] internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteSymbolFinderService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallbackDispatcher() { } private FindLiteralsServerCallback GetFindLiteralsCallback(RemoteServiceCallbackId callbackId) => (FindLiteralsServerCallback)GetCallback(callbackId); private FindReferencesServerCallback GetFindReferencesCallback(RemoteServiceCallbackId callbackId) => (FindReferencesServerCallback)GetCallback(callbackId); // references public ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnCompletedAsync(cancellationToken); public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnDefinitionFoundAsync(symbolGroup, cancellationToken); public ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnFindInDocumentCompletedAsync(documentId, cancellationToken); public ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnFindInDocumentStartedAsync(documentId, cancellationToken); public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup symbolGroup, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnReferenceFoundAsync(symbolGroup, definition, reference, cancellationToken); public ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindReferencesCallback(callbackId).OnStartedAsync(cancellationToken); // literals public ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetFindLiteralsCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetFindLiteralsCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken) => GetFindLiteralsCallback(callbackId).OnLiteralReferenceFoundAsync(documentId, span, cancellationToken); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/LanguageServer/Protocol/Handler/Formatting/FormatDocumentHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentFormattingName)] internal class FormatDocumentHandler : AbstractFormatDocumentHandlerBase<LSP.DocumentFormattingParams, LSP.TextEdit[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentHandler() { } public override string Method => LSP.Methods.TextDocumentFormattingName; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DocumentFormattingParams request) => request.TextDocument; public override Task<LSP.TextEdit[]> HandleRequestAsync( LSP.DocumentFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(context, request.Options, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentFormattingName)] internal class FormatDocumentHandler : AbstractFormatDocumentHandlerBase<LSP.DocumentFormattingParams, LSP.TextEdit[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentHandler() { } public override string Method => LSP.Methods.TextDocumentFormattingName; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DocumentFormattingParams request) => request.TextDocument; public override Task<LSP.TextEdit[]> HandleRequestAsync( LSP.DocumentFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(context, request.Options, cancellationToken); } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedSequencePointsWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.DiaSymReader { internal sealed class SymUnmanagedSequencePointsWriter { private readonly SymUnmanagedWriter _writer; private int _currentDocumentIndex; private int _count; private int[] _offsets; private int[] _startLines; private int[] _startColumns; private int[] _endLines; private int[] _endColumns; public SymUnmanagedSequencePointsWriter(SymUnmanagedWriter writer, int capacity = 64) { if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity)); } _writer = writer ?? throw new ArgumentNullException(nameof(writer)); _currentDocumentIndex = -1; _offsets = new int[capacity]; _startLines = new int[capacity]; _startColumns = new int[capacity]; _endLines = new int[capacity]; _endColumns = new int[capacity]; } private void EnsureCapacity(int length) { if (length > _offsets.Length) { int newLength = Math.Max(length, (_offsets.Length + 1) * 2); Array.Resize(ref _offsets, newLength); Array.Resize(ref _startLines, newLength); Array.Resize(ref _startColumns, newLength); Array.Resize(ref _endLines, newLength); Array.Resize(ref _endColumns, newLength); } } private void Clear() { _currentDocumentIndex = -1; _count = 0; } public void Add(int documentIndex, int offset, int startLine, int startColumn, int endLine, int endColumn) { if (documentIndex < 0) { throw new ArgumentOutOfRangeException(nameof(documentIndex)); } if (_currentDocumentIndex != documentIndex) { if (_currentDocumentIndex != -1) { Flush(); } _currentDocumentIndex = documentIndex; } int index = _count++; EnsureCapacity(_count); _offsets[index] = offset; _startLines[index] = startLine; _startColumns[index] = startColumn; _endLines[index] = endLine; _endColumns[index] = endColumn; } public void Flush() { if (_count > 0) { _writer.DefineSequencePoints( _currentDocumentIndex, _count, _offsets, _startLines, _startColumns, _endLines, _endColumns); } 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. #nullable disable using System; namespace Microsoft.DiaSymReader { internal sealed class SymUnmanagedSequencePointsWriter { private readonly SymUnmanagedWriter _writer; private int _currentDocumentIndex; private int _count; private int[] _offsets; private int[] _startLines; private int[] _startColumns; private int[] _endLines; private int[] _endColumns; public SymUnmanagedSequencePointsWriter(SymUnmanagedWriter writer, int capacity = 64) { if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity)); } _writer = writer ?? throw new ArgumentNullException(nameof(writer)); _currentDocumentIndex = -1; _offsets = new int[capacity]; _startLines = new int[capacity]; _startColumns = new int[capacity]; _endLines = new int[capacity]; _endColumns = new int[capacity]; } private void EnsureCapacity(int length) { if (length > _offsets.Length) { int newLength = Math.Max(length, (_offsets.Length + 1) * 2); Array.Resize(ref _offsets, newLength); Array.Resize(ref _startLines, newLength); Array.Resize(ref _startColumns, newLength); Array.Resize(ref _endLines, newLength); Array.Resize(ref _endColumns, newLength); } } private void Clear() { _currentDocumentIndex = -1; _count = 0; } public void Add(int documentIndex, int offset, int startLine, int startColumn, int endLine, int endColumn) { if (documentIndex < 0) { throw new ArgumentOutOfRangeException(nameof(documentIndex)); } if (_currentDocumentIndex != documentIndex) { if (_currentDocumentIndex != -1) { Flush(); } _currentDocumentIndex = documentIndex; } int index = _count++; EnsureCapacity(_count); _offsets[index] = offset; _startLines[index] = startLine; _startColumns[index] = startColumn; _endLines[index] = endLine; _endColumns[index] = endColumn; } public void Flush() { if (_count > 0) { _writer.DefineSequencePoints( _currentDocumentIndex, _count, _offsets, _startLines, _startColumns, _endLines, _endColumns); } Clear(); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/CSharpTest/CodeActions/AddAwait/AddAwaitTests.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.AddAwait { [Trait(Traits.Feature, Traits.Features.AddAwait)] public class AddAwaitTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpAddAwaitCodeRefactoringProvider(); [Fact] public async Task Simple() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = GetNumberAsync()[||]; } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] public async Task SimpleWithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = GetNumberAsync()[||]; } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync().ConfigureAwait(false); } }", index: 1); } [Fact] public async Task InArgument() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync(int argument) { var x = GetNumberAsync(arg[||]ument); } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync(int argument) { var x = await GetNumberAsync(argument); } }"); } [Fact] public async Task InvocationInArgument() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(GetNumberAsync()[||]); } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(await GetNumberAsync()); } }"); } [Fact] public async Task InvocationInArgumentWithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(GetNumberAsync()[||]); } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(await GetNumberAsync().ConfigureAwait(false)); } }", index: 1); } [Fact] public async Task AlreadyAwaited() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync()[||]; } }"); } [Fact] public async Task AlreadyAwaitedAndConfigured() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync()[||].ConfigureAwait(false); } }"); } [Fact] public async Task AlreadyAwaitedAndConfigured2() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync().ConfigureAwait(false)[||]; } }"); } [Fact] public async Task SimpleWithTrivia() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment GetNumberAsync()[||] /* comment */ } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment await GetNumberAsync()[||] /* comment */ } }"); } [Fact] public async Task SimpleWithTrivia2() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ GetNumberAsync()[||] // comment } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ await GetNumberAsync()[||] // comment } }"); } [Fact] public async Task SimpleWithTriviaWithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment GetNumberAsync()[||] /* comment */ } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment await GetNumberAsync().ConfigureAwait(false) /* comment */ } }", index: 1); } [Fact] public async Task SimpleWithTrivia2WithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ GetNumberAsync()[||] // comment } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ await GetNumberAsync().ConfigureAwait(false) // comment } }", index: 1); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task OnSemiColon() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = GetNumberAsync();[||] } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task Selection() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = [|GetNumberAsync()|]; } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task Selection2() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { [|var x = GetNumberAsync();|] } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] public async Task ChainedInvocation() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { Task<int> GetNumberAsync() => throw null; async void M() { var x = GetNumberAsync()[||].ToString(); } }"); } [Fact] public async Task ChainedInvocation_ExpressionOfInvalidInvocation() { await TestInRegularAndScript1Async(@" using System.Threading.Tasks; class Program { Task<int> GetNumberAsync() => throw null; async void M() { var x = GetNumberAsync()[||].Invalid(); } }", @" using System.Threading.Tasks; class Program { Task<int> GetNumberAsync() => throw null; async void M() { var x = (await GetNumberAsync()).Invalid(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand1() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return [|Test()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return await Test(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_WithLeadingTrivia1() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return // Useful comment [|Test()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return // Useful comment await Test(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|true ? Test() /* true */ : Test()|] /* false */; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (true ? Test() /* true */ : Test()) /* false */; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|true ? Test() // aaa : Test()|] // bbb ; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (true ? Test() // aaa : Test()) // bbb ; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|null /* 0 */ ?? Test()|] /* 1 */; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null /* 0 */ ?? Test()) /* 1 */; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|null // aaa ?? Test()|] // bbb ; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null // aaa ?? Test()) // bbb ; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test2() { return [|null /* 0 */ as Task<int>|] /* 1 */; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test2() { return await (null /* 0 */ as Task<int>) /* 1 */; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|null // aaa as Task<int>|] // bbb ; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null // aaa as Task<int>) // bbb ; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TaskNotAwaited() { var initial = @"using System; using System.Threading.Tasks; class Program { async void Test() { [|Task.Delay(3)|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TaskNotAwaited_WithLeadingTrivia() { var initial = @"using System; using System.Threading.Tasks; class Program { async void Test() { // Useful comment [|Task.Delay(3)|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async void Test() { // Useful comment await Task.Delay(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { [|AwaitableFunction()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { await AwaitableFunction(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited_WithLeadingTrivia() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { // Useful comment [|AwaitableFunction()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { // Useful comment await AwaitableFunction(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited_WithLeadingTrivia1() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { var i = 0; [|AwaitableFunction()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { var i = 0; await AwaitableFunction(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { int myInt = [|MyIntMethodAsync()|]; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { int myInt = await MyIntMethodAsync(); } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversion() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = [|MyIntMethodAsync()|]; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = await MyIntMethodAsync(); } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction() { await TestMissingAsync(@"using System.Threading.Tasks; class TestClass { private Task MyTestMethod1Async() { long myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversionInAsyncFunction() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = [|MyIntMethodAsync()|]; } private Task<object> MyIntMethodAsync() { return Task.FromResult(new object()); } }", @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = [|await MyIntMethodAsync()|]; } private Task<object> MyIntMethodAsync() { return Task.FromResult(new object()); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression2() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression3() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = () => { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression3_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = await MyIntMethodAsync(); return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression4() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression4_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression5() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression6() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression7() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression7_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression8() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = delegate { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression8_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = [|await MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestTernaryOperator() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return [|true ? Task.FromResult(0) : Task.FromResult(1)|]; } }", @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return await (true ? Task.FromResult(0) : Task.FromResult(1)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestNullCoalescingOperator() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return [|null ?? Task.FromResult(1)|]; } }", @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return await (null ?? Task.FromResult(1)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAsExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return [|null as Task<int>|]; } }", @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return await (null as Task<int>); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] [WorkItem(1345322, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322")] public async Task TestOnTaskTypeItself() { await TestMissingAsync( @"using System.Threading.Tasks; class Program { static async [||]Task Main(string[] args) { } } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.AddAwait; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.AddAwait { [Trait(Traits.Feature, Traits.Features.AddAwait)] public class AddAwaitTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpAddAwaitCodeRefactoringProvider(); [Fact] public async Task Simple() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = GetNumberAsync()[||]; } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] public async Task SimpleWithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = GetNumberAsync()[||]; } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync().ConfigureAwait(false); } }", index: 1); } [Fact] public async Task InArgument() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync(int argument) { var x = GetNumberAsync(arg[||]ument); } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync(int argument) { var x = await GetNumberAsync(argument); } }"); } [Fact] public async Task InvocationInArgument() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(GetNumberAsync()[||]); } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(await GetNumberAsync()); } }"); } [Fact] public async Task InvocationInArgumentWithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(GetNumberAsync()[||]); } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { M(await GetNumberAsync().ConfigureAwait(false)); } }", index: 1); } [Fact] public async Task AlreadyAwaited() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync()[||]; } }"); } [Fact] public async Task AlreadyAwaitedAndConfigured() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync()[||].ConfigureAwait(false); } }"); } [Fact] public async Task AlreadyAwaitedAndConfigured2() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync().ConfigureAwait(false)[||]; } }"); } [Fact] public async Task SimpleWithTrivia() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment GetNumberAsync()[||] /* comment */ } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment await GetNumberAsync()[||] /* comment */ } }"); } [Fact] public async Task SimpleWithTrivia2() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ GetNumberAsync()[||] // comment } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ await GetNumberAsync()[||] // comment } }"); } [Fact] public async Task SimpleWithTriviaWithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment GetNumberAsync()[||] /* comment */ } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = // comment await GetNumberAsync().ConfigureAwait(false) /* comment */ } }", index: 1); } [Fact] public async Task SimpleWithTrivia2WithConfigureAwait() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ GetNumberAsync()[||] // comment } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = /* comment */ await GetNumberAsync().ConfigureAwait(false) // comment } }", index: 1); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task OnSemiColon() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = GetNumberAsync();[||] } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task Selection() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = [|GetNumberAsync()|]; } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task Selection2() { await TestInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { [|var x = GetNumberAsync();|] } }", @" using System.Threading.Tasks; class Program { async Task<int> GetNumberAsync() { var x = await GetNumberAsync(); } }"); } [Fact] public async Task ChainedInvocation() { await TestMissingInRegularAndScriptAsync(@" using System.Threading.Tasks; class Program { Task<int> GetNumberAsync() => throw null; async void M() { var x = GetNumberAsync()[||].ToString(); } }"); } [Fact] public async Task ChainedInvocation_ExpressionOfInvalidInvocation() { await TestInRegularAndScript1Async(@" using System.Threading.Tasks; class Program { Task<int> GetNumberAsync() => throw null; async void M() { var x = GetNumberAsync()[||].Invalid(); } }", @" using System.Threading.Tasks; class Program { Task<int> GetNumberAsync() => throw null; async void M() { var x = (await GetNumberAsync()).Invalid(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand1() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return [|Test()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return await Test(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_WithLeadingTrivia1() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return // Useful comment [|Test()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() { return 3; } async Task<int> Test2() { return // Useful comment await Test(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|true ? Test() /* true */ : Test()|] /* false */; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (true ? Test() /* true */ : Test()) /* false */; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_ConditionalExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|true ? Test() // aaa : Test()|] // bbb ; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (true ? Test() // aaa : Test()) // bbb ; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|null /* 0 */ ?? Test()|] /* 1 */; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null /* 0 */ ?? Test()) /* 1 */; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_NullCoalescingExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|null // aaa ?? Test()|] // bbb ; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null // aaa ?? Test()) // bbb ; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_SingleLine() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test2() { return [|null /* 0 */ as Task<int>|] /* 1 */; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test2() { return await (null /* 0 */ as Task<int>) /* 1 */; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task BadAsyncReturnOperand_AsExpressionWithTrailingTrivia_Multiline() { var initial = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return [|null // aaa as Task<int>|] // bbb ; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async Task<int> Test() => 3; async Task<int> Test2() { return await (null // aaa as Task<int>) // bbb ; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TaskNotAwaited() { var initial = @"using System; using System.Threading.Tasks; class Program { async void Test() { [|Task.Delay(3)|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async void Test() { await Task.Delay(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TaskNotAwaited_WithLeadingTrivia() { var initial = @"using System; using System.Threading.Tasks; class Program { async void Test() { // Useful comment [|Task.Delay(3)|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { async void Test() { // Useful comment await Task.Delay(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { [|AwaitableFunction()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { await AwaitableFunction(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited_WithLeadingTrivia() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { // Useful comment [|AwaitableFunction()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { // Useful comment await AwaitableFunction(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task FunctionNotAwaited_WithLeadingTrivia1() { var initial = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { var i = 0; [|AwaitableFunction()|]; } }"; var expected = @"using System; using System.Threading.Tasks; class Program { Task AwaitableFunction() { return Task.FromResult(true); } async void Test() { var i = 0; await AwaitableFunction(); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { int myInt = [|MyIntMethodAsync()|]; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { int myInt = await MyIntMethodAsync(); } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversion() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = [|MyIntMethodAsync()|]; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = await MyIntMethodAsync(); } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversionInNonAsyncFunction() { await TestMissingAsync(@"using System.Threading.Tasks; class TestClass { private Task MyTestMethod1Async() { long myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpressionWithConversionInAsyncFunction() { await TestInRegularAndScriptAsync( @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = [|MyIntMethodAsync()|]; } private Task<object> MyIntMethodAsync() { return Task.FromResult(new object()); } }", @"using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { long myInt = [|await MyIntMethodAsync()|]; } private Task<object> MyIntMethodAsync() { return Task.FromResult(new object()); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression2() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression3() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = () => { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression3_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> lambda = async () => { int myInt = await MyIntMethodAsync(); return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression4() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression4_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action lambda = async () => { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression5() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression6() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression7() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression7_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Action @delegate = async delegate { int myInt = await MyIntMethodAsync(); }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression8() { await TestMissingAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = delegate { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAssignmentExpression8_1() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = [|MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }", @"using System; using System.Threading.Tasks; class TestClass { private async Task MyTestMethod1Async() { Func<Task> @delegate = async delegate { int myInt = [|await MyIntMethodAsync()|]; return Task.CompletedTask; }; } private Task<int> MyIntMethodAsync() { return Task.FromResult(result: 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestTernaryOperator() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return [|true ? Task.FromResult(0) : Task.FromResult(1)|]; } }", @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return await (true ? Task.FromResult(0) : Task.FromResult(1)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestNullCoalescingOperator() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return [|null ?? Task.FromResult(1)|]; } }", @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return await (null ?? Task.FromResult(1)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] public async Task TestAsExpression() { await TestInRegularAndScriptAsync( @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return [|null as Task<int>|]; } }", @"using System; using System.Threading.Tasks; class Program { async Task<int> A() { return await (null as Task<int>); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAwait)] [WorkItem(1345322, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1345322")] public async Task TestOnTaskTypeItself() { await TestMissingAsync( @"using System.Threading.Tasks; class Program { static async [||]Task Main(string[] args) { } } "); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorOverloadResolutionResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class BinaryOperatorOverloadResolutionResult { public readonly ArrayBuilder<BinaryOperatorAnalysisResult> Results; private BinaryOperatorOverloadResolutionResult() { this.Results = new ArrayBuilder<BinaryOperatorAnalysisResult>(10); } public bool AnyValid() { foreach (var result in Results) { if (result.IsValid) { return true; } } return false; } public bool SingleValid() { bool oneValid = false; foreach (var result in Results) { if (result.IsValid) { if (oneValid) { return false; } oneValid = true; } } return oneValid; } public BinaryOperatorAnalysisResult Best { get { BinaryOperatorAnalysisResult best = default(BinaryOperatorAnalysisResult); foreach (var result in Results) { if (result.IsValid) { if (best.IsValid) { // More than one best applicable method return default(BinaryOperatorAnalysisResult); } best = result; } } return best; } } #if DEBUG public string Dump() { if (Results.Count == 0) { return "Overload resolution failed because there were no candidate operators."; } var sb = new StringBuilder(); if (this.Best.HasValue) { sb.AppendLine("Overload resolution succeeded and chose " + this.Best.Signature.ToString()); } else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1) { sb.AppendLine("Overload resolution failed because of ambiguous possible best operators."); } else { sb.AppendLine("Overload resolution failed because no operator was applicable."); } sb.AppendLine("Detailed results:"); foreach (var result in Results) { sb.AppendFormat("operator: {0} reason: {1}\n", result.Signature.ToString(), result.Kind.ToString()); } return sb.ToString(); } private int CountKind(OperatorAnalysisResultKind kind) { int count = 0; for (int i = 0, n = this.Results.Count; i < n; i++) { if (this.Results[i].Kind == kind) { count++; } } return count; } #endif #region "Poolable" public static BinaryOperatorOverloadResolutionResult GetInstance() { return Pool.Allocate(); } public void Free() { Clear(); Pool.Free(this); } public void Clear() { this.Results.Clear(); } public static readonly ObjectPool<BinaryOperatorOverloadResolutionResult> Pool = CreatePool(); private static ObjectPool<BinaryOperatorOverloadResolutionResult> CreatePool() { ObjectPool<BinaryOperatorOverloadResolutionResult> pool = null; pool = new ObjectPool<BinaryOperatorOverloadResolutionResult>(() => new BinaryOperatorOverloadResolutionResult(), 10); return pool; } #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.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class BinaryOperatorOverloadResolutionResult { public readonly ArrayBuilder<BinaryOperatorAnalysisResult> Results; private BinaryOperatorOverloadResolutionResult() { this.Results = new ArrayBuilder<BinaryOperatorAnalysisResult>(10); } public bool AnyValid() { foreach (var result in Results) { if (result.IsValid) { return true; } } return false; } public bool SingleValid() { bool oneValid = false; foreach (var result in Results) { if (result.IsValid) { if (oneValid) { return false; } oneValid = true; } } return oneValid; } public BinaryOperatorAnalysisResult Best { get { BinaryOperatorAnalysisResult best = default(BinaryOperatorAnalysisResult); foreach (var result in Results) { if (result.IsValid) { if (best.IsValid) { // More than one best applicable method return default(BinaryOperatorAnalysisResult); } best = result; } } return best; } } #if DEBUG public string Dump() { if (Results.Count == 0) { return "Overload resolution failed because there were no candidate operators."; } var sb = new StringBuilder(); if (this.Best.HasValue) { sb.AppendLine("Overload resolution succeeded and chose " + this.Best.Signature.ToString()); } else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1) { sb.AppendLine("Overload resolution failed because of ambiguous possible best operators."); } else { sb.AppendLine("Overload resolution failed because no operator was applicable."); } sb.AppendLine("Detailed results:"); foreach (var result in Results) { sb.AppendFormat("operator: {0} reason: {1}\n", result.Signature.ToString(), result.Kind.ToString()); } return sb.ToString(); } private int CountKind(OperatorAnalysisResultKind kind) { int count = 0; for (int i = 0, n = this.Results.Count; i < n; i++) { if (this.Results[i].Kind == kind) { count++; } } return count; } #endif #region "Poolable" public static BinaryOperatorOverloadResolutionResult GetInstance() { return Pool.Allocate(); } public void Free() { Clear(); Pool.Free(this); } public void Clear() { this.Results.Clear(); } public static readonly ObjectPool<BinaryOperatorOverloadResolutionResult> Pool = CreatePool(); private static ObjectPool<BinaryOperatorOverloadResolutionResult> CreatePool() { ObjectPool<BinaryOperatorOverloadResolutionResult> pool = null; pool = new ObjectPool<BinaryOperatorOverloadResolutionResult>(() => new BinaryOperatorOverloadResolutionResult(), 10); return pool; } #endregion } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesProgress.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.FindSymbols { /// <summary> /// A does-nothing version of the <see cref="IFindReferencesProgress"/>. Useful for /// clients that have no need to report progress as they work. /// </summary> internal class NoOpFindReferencesProgress : IFindReferencesProgress { public static readonly IFindReferencesProgress Instance = new NoOpFindReferencesProgress(); private NoOpFindReferencesProgress() { } public void ReportProgress(int current, int maximum) { } public void OnCompleted() { } public void OnStarted() { } public void OnDefinitionFound(ISymbol symbol) { } public void OnReferenceFound(ISymbol symbol, ReferenceLocation location) { } public void OnFindInDocumentStarted(Document document) { } public void OnFindInDocumentCompleted(Document document) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.FindSymbols { /// <summary> /// A does-nothing version of the <see cref="IFindReferencesProgress"/>. Useful for /// clients that have no need to report progress as they work. /// </summary> internal class NoOpFindReferencesProgress : IFindReferencesProgress { public static readonly IFindReferencesProgress Instance = new NoOpFindReferencesProgress(); private NoOpFindReferencesProgress() { } public void ReportProgress(int current, int maximum) { } public void OnCompleted() { } public void OnStarted() { } public void OnDefinitionFound(ISymbol symbol) { } public void OnReferenceFound(ISymbol symbol, ReferenceLocation location) { } public void OnFindInDocumentStarted(Document document) { } public void OnFindInDocumentCompleted(Document document) { } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable /// the analysis to take place without tracking exceptions or repeating the analysis of a finally block /// for each exit from a try statement. The shortcut results in a slightly less precise /// (but still conservative) analysis, but that less precise analysis is all that is required for /// the language specification. The most significant shortcut is that we do not track the state /// where exceptions can arise. That does not affect the soundness for most analyses, but for those /// analyses whose soundness would be affected (e.g. "data flows out"), we track "unassignments" to keep /// the analysis sound. /// </summary> /// <remarks> /// Formally, this is a fairly conventional lattice flow analysis (<see /// href="https://en.wikipedia.org/wiki/Data-flow_analysis"/>) that moves upward through the <see cref="Join(ref /// TLocalState, ref TLocalState)"/> operation. /// </remarks> internal abstract partial class AbstractFlowPass<TLocalState, TLocalFunctionState> : BoundTreeVisitor where TLocalState : AbstractFlowPass<TLocalState, TLocalFunctionState>.ILocalState where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState { protected int _recursionDepth; /// <summary> /// The compilation in which the analysis is taking place. This is needed to determine which /// conditional methods will be compiled and which will be omitted. /// </summary> protected readonly CSharpCompilation compilation; /// <summary> /// The method whose body is being analyzed, or the field whose initializer is being analyzed. /// May be a top-level member or a lambda or local function. It is used for /// references to method parameters. Thus, '_symbol' should not be used directly, but /// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used /// instead. _symbol is null during speculative binding. /// </summary> protected readonly Symbol _symbol; /// <summary> /// Reflects the enclosing member, lambda or local function at the current location (in the bound tree). /// </summary> protected Symbol CurrentSymbol; /// <summary> /// The bound node of the method or initializer being analyzed. /// </summary> protected readonly BoundNode methodMainNode; /// <summary> /// The flow analysis state at each label, computed by calling <see cref="Join(ref /// TLocalState, ref TLocalState)"/> on the state from branches to that label with the state /// when we fall into the label. Entries are created when the label is encountered. One /// case deserves special attention: when the destination of the branch is a label earlier /// in the code, it is possible (though rarely occurs in practice) that we are changing the /// state at a label that we've already analyzed. In that case we run another pass of the /// analysis to allow those changes to propagate. This repeats until no further changes to /// the state of these labels occurs. This can result in quadratic performance in unlikely /// but possible code such as this: "int x; if (cond) goto l1; x = 3; l5: print x; l4: goto /// l5; l3: goto l4; l2: goto l3; l1: goto l2;" /// </summary> private readonly PooledDictionary<LabelSymbol, TLocalState> _labels; /// <summary> /// Set to true after an analysis scan if the analysis was incomplete due to state changing /// after it was used by another analysis component. In this case the caller scans again (until /// this is false). Since the analysis proceeds by monotonically changing the state computed /// at each label, this must terminate. /// </summary> protected bool stateChangedAfterUse; /// <summary> /// All of the labels seen so far in this forward scan of the body /// </summary> private PooledHashSet<BoundStatement> _labelsSeen; /// <summary> /// Pending escapes generated in the current scope (or more deeply nested scopes). When jump /// statements (goto, break, continue, return) are processed, they are placed in the /// pendingBranches buffer to be processed later by the code handling the destination /// statement. As a special case, the processing of try-finally statements might modify the /// contents of the pendingBranches buffer to take into account the behavior of /// "intervening" finally clauses. /// </summary> protected ArrayBuilder<PendingBranch> PendingBranches { get; private set; } /// <summary> /// The definite assignment and/or reachability state at the point currently being analyzed. /// </summary> protected TLocalState State; protected TLocalState StateWhenTrue; protected TLocalState StateWhenFalse; protected bool IsConditionalState; /// <summary> /// Indicates that the transfer function for a particular node (the function mapping the /// state before the node to the state after the node) is not monotonic, in the sense that /// it can change the state in either direction in the lattice. If the transfer function is /// monotonic, the transfer function can only change the state toward the <see /// cref="UnreachableState"/>. Reachability and definite assignment are monotonic, and /// permit a more efficient analysis. Region analysis and nullable analysis are not /// monotonic. This is just an optimization; we could treat all of them as nonmonotonic /// without much loss of performance. In fact, this only affects the analysis of (relatively /// rare) try statements, and is only a slight optimization. /// </summary> private readonly bool _nonMonotonicTransfer; protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state) { SetConditionalState(state.whenTrue, state.whenFalse); } protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse) { IsConditionalState = true; State = default(TLocalState); StateWhenTrue = whenTrue; StateWhenFalse = whenFalse; } protected void SetState(TLocalState newState) { Debug.Assert(newState != null); StateWhenTrue = StateWhenFalse = default(TLocalState); IsConditionalState = false; State = newState; } protected void Split() { if (!IsConditionalState) { SetConditionalState(State, State.Clone()); } } protected void Unsplit() { if (IsConditionalState) { Join(ref StateWhenTrue, ref StateWhenFalse); SetState(StateWhenTrue); } } /// <summary> /// Where all diagnostics are deposited. /// </summary> protected DiagnosticBag Diagnostics { get; } #region Region // For region analysis, we maintain some extra data. protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region protected readonly BoundNode firstInRegion, lastInRegion; protected readonly bool TrackingRegions; /// <summary> /// A cache of the state at the backward branch point of each loop. This is not needed /// during normal flow analysis, but is needed for DataFlowsOut region analysis. /// </summary> private readonly Dictionary<BoundLoopStatement, TLocalState> _loopHeadState; #endregion Region protected AbstractFlowPass( CSharpCompilation compilation, Symbol symbol, BoundNode node, BoundNode firstInRegion = null, BoundNode lastInRegion = null, bool trackRegions = false, bool nonMonotonicTransferFunction = false) { Debug.Assert(node != null); if (firstInRegion != null && lastInRegion != null) { trackRegions = true; } if (trackRegions) { Debug.Assert(firstInRegion != null); Debug.Assert(lastInRegion != null); int startLocation = firstInRegion.Syntax.SpanStart; int endLocation = lastInRegion.Syntax.Span.End; int length = endLocation - startLocation; Debug.Assert(length >= 0, "last comes before first"); this.RegionSpan = new TextSpan(startLocation, length); } PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); _labels = PooledDictionary<LabelSymbol, TLocalState>.GetInstance(); this.Diagnostics = DiagnosticBag.GetInstance(); this.compilation = compilation; _symbol = symbol; CurrentSymbol = symbol; this.methodMainNode = node; this.firstInRegion = firstInRegion; this.lastInRegion = lastInRegion; _loopHeadState = new Dictionary<BoundLoopStatement, TLocalState>(ReferenceEqualityComparer.Instance); TrackingRegions = trackRegions; _nonMonotonicTransfer = nonMonotonicTransferFunction; } protected abstract string Dump(TLocalState state); protected string Dump() { return IsConditionalState ? $"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}" : Dump(this.State); } #if DEBUG protected string DumpLabels() { StringBuilder result = new StringBuilder(); result.Append("Labels{"); bool first = true; foreach (var key in _labels.Keys) { if (!first) { result.Append(", "); } string name = key.Name; if (string.IsNullOrEmpty(name)) { name = "<Label>" + key.GetHashCode(); } result.Append(name).Append(": ").Append(this.Dump(_labels[key])); first = false; } result.Append("}"); return result.ToString(); } #endif private void EnterRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before) { EnterRegion(); } } /// <summary> /// Subclasses may override EnterRegion to perform any actions at the entry to the region. /// </summary> protected virtual void EnterRegion() { Debug.Assert(this.regionPlace == RegionPlace.Before); this.regionPlace = RegionPlace.Inside; } private void LeaveRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside) { LeaveRegion(); } } /// <summary> /// Subclasses may override LeaveRegion to perform any action at the end of the region. /// </summary> protected virtual void LeaveRegion() { Debug.Assert(IsInside); this.regionPlace = RegionPlace.After; } protected readonly TextSpan RegionSpan; protected bool RegionContains(TextSpan span) { // TODO: There are no scenarios involving a zero-length span // currently. If the assert fails, add a corresponding test. Debug.Assert(span.Length > 0); if (span.Length == 0) { return RegionSpan.Contains(span.Start); } return RegionSpan.Contains(span); } protected bool IsInside { get { return regionPlace == RegionPlace.Inside; } } protected virtual void EnterParameters(ImmutableArray<ParameterSymbol> parameters) { foreach (var parameter in parameters) { EnterParameter(parameter); } } protected virtual void EnterParameter(ParameterSymbol parameter) { } protected virtual void LeaveParameters( ImmutableArray<ParameterSymbol> parameters, SyntaxNode syntax, Location location) { foreach (ParameterSymbol parameter in parameters) { LeaveParameter(parameter, syntax, location); } } protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location) { } public override BoundNode Visit(BoundNode node) { return VisitAlways(node); } protected BoundNode VisitAlways(BoundNode node) { BoundNode result = null; // We scan even expressions, because we must process lambdas contained within them. if (node != null) { EnterRegionIfNeeded(node); VisitWithStackGuard(node); LeaveRegionIfNeeded(node); } return result; } [DebuggerStepThrough] private BoundNode VisitWithStackGuard(BoundNode node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } [DebuggerStepThrough] protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; // just let the original exception bubble up. } /// <summary> /// A pending branch. These are created for a return, break, continue, goto statement, /// yield return, yield break, await expression, and await foreach/using. The idea is that /// we don't know if the branch will eventually reach its destination because of an /// intervening finally block that cannot complete normally. So we store them up and handle /// them as we complete processing each construct. At the end of a block, if there are any /// pending branches to a label in that block we process the branch. Otherwise we relay it /// up to the enclosing construct as a pending branch of the enclosing construct. /// </summary> internal class PendingBranch { public readonly BoundNode Branch; public bool IsConditionalState; public TLocalState State; public TLocalState StateWhenTrue; public TLocalState StateWhenFalse; public readonly LabelSymbol Label; public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default, TLocalState stateWhenFalse = default) { this.Branch = branch; this.State = state.Clone(); this.IsConditionalState = isConditionalState; if (isConditionalState) { this.StateWhenTrue = stateWhenTrue.Clone(); this.StateWhenFalse = stateWhenFalse.Clone(); } this.Label = label; } } /// <summary> /// Perform a single pass of flow analysis. Note that after this pass, /// this.backwardBranchChanged indicates if a further pass is required. /// </summary> protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion) { var oldPending = SavePending(); Visit(methodMainNode); this.Unsplit(); RestorePending(oldPending); if (TrackingRegions && regionPlace != RegionPlace.After) { badRegion = true; } ImmutableArray<PendingBranch> result = RemoveReturns(); return result; } protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion, Optional<TLocalState> initialState = default) { ImmutableArray<PendingBranch> returns; do { // the entry point of a method is assumed reachable regionPlace = RegionPlace.Before; this.State = initialState.HasValue ? initialState.Value : TopState(); PendingBranches.Clear(); this.stateChangedAfterUse = false; this.Diagnostics.Clear(); returns = this.Scan(ref badRegion); } while (this.stateChangedAfterUse); return returns; } protected virtual void Free() { this.Diagnostics.Free(); PendingBranches.Free(); _labelsSeen.Free(); _labels.Free(); } /// <summary> /// If a method is currently being analyzed returns its parameters, returns an empty array /// otherwise. /// </summary> protected ImmutableArray<ParameterSymbol> MethodParameters { get { var method = _symbol as MethodSymbol; return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters; } } /// <summary> /// If a method is currently being analyzed returns its 'this' parameter, returns null /// otherwise. /// </summary> protected ParameterSymbol MethodThisParameter { get { ParameterSymbol thisParameter = null; (_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter); return thisParameter; } } /// <summary> /// Specifies whether or not method's out parameters should be analyzed. If there's more /// than one location in the method being analyzed, then the method is partial and we prefer /// to report an out parameter in partial method error. /// </summary> /// <param name="location">location to be used</param> /// <returns>true if the out parameters of the method should be analyzed</returns> protected bool ShouldAnalyzeOutParameters(out Location location) { var method = _symbol as MethodSymbol; if ((object)method == null || method.Locations.Length != 1) { location = null; return false; } else { location = method.Locations[0]; return true; } } /// <summary> /// Return the flow analysis state associated with a label. /// </summary> /// <param name="label"></param> /// <returns></returns> protected virtual TLocalState LabelState(LabelSymbol label) { TLocalState result; if (_labels.TryGetValue(label, out result)) { return result; } result = UnreachableState(); _labels.Add(label, result); return result; } /// <summary> /// Return to the caller the set of pending return statements. /// </summary> /// <returns></returns> protected virtual ImmutableArray<PendingBranch> RemoveReturns() { ImmutableArray<PendingBranch> result; result = PendingBranches.ToImmutable(); PendingBranches.Clear(); // The caller should have handled and cleared labelsSeen. Debug.Assert(_labelsSeen.Count == 0); return result; } /// <summary> /// Set the current state to one that indicates that it is unreachable. /// </summary> protected void SetUnreachable() { this.State = UnreachableState(); } protected void VisitLvalue(BoundExpression node) { EnterRegionIfNeeded(node); switch (node?.Kind) { case BoundKind.Parameter: VisitLvalueParameter((BoundParameter)node); break; case BoundKind.Local: VisitLvalue((BoundLocal)node); break; case BoundKind.ThisReference: case BoundKind.BaseReference: break; case BoundKind.PropertyAccess: var access = (BoundPropertyAccess)node; if (Binder.AccessingAutoPropertyFromConstructor(access, _symbol)) { var backingField = (access.PropertySymbol as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(access.ReceiverOpt, backingField); break; } } goto default; case BoundKind.FieldAccess: { BoundFieldAccess node1 = (BoundFieldAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol); break; } case BoundKind.EventAccess: { BoundEventAccess node1 = (BoundEventAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField); break; } case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: ((BoundTupleExpression)node).VisitAllElements((x, self) => self.VisitLvalue(x), this); break; default: VisitRvalue(node); break; } LeaveRegionIfNeeded(node); } protected virtual void VisitLvalue(BoundLocal node) { } /// <summary> /// Visit a boolean condition expression. /// </summary> /// <param name="node"></param> protected void VisitCondition(BoundExpression node) { Visit(node); AdjustConditionalState(node); } private void AdjustConditionalState(BoundExpression node) { if (IsConstantTrue(node)) { Unsplit(); SetConditionalState(this.State, UnreachableState()); } else if (IsConstantFalse(node)) { Unsplit(); SetConditionalState(UnreachableState(), this.State); } else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean) { // a dynamic type or a type with operator true/false Unsplit(); } Split(); } /// <summary> /// Visit a general expression, where we will only need to determine if variables are /// assigned (or not). That is, we will not be needing AssignedWhenTrue and /// AssignedWhenFalse. /// </summary> /// <param name="isKnownToBeAnLvalue">True when visiting an rvalue that will actually be used as an lvalue, /// for example a ref parameter when simulating a read of it, or an argument corresponding to an in parameter</param> protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false) { Visit(node); Unsplit(); } /// <summary> /// Visit a statement. /// </summary> [DebuggerHidden] protected virtual void VisitStatement(BoundStatement statement) { Visit(statement); Debug.Assert(!this.IsConditionalState); } protected static bool IsConstantTrue(BoundExpression node) { return node.ConstantValue == ConstantValue.True; } protected static bool IsConstantFalse(BoundExpression node) { return node.ConstantValue == ConstantValue.False; } protected static bool IsConstantNull(BoundExpression node) { return node.ConstantValue == ConstantValue.Null; } /// <summary> /// Called at the point in a loop where the backwards branch would go to. /// </summary> private void LoopHead(BoundLoopStatement node) { TLocalState previousState; if (_loopHeadState.TryGetValue(node, out previousState)) { Join(ref this.State, ref previousState); } _loopHeadState[node] = this.State.Clone(); } /// <summary> /// Called at the point in a loop where the backward branch is placed. /// </summary> private void LoopTail(BoundLoopStatement node) { var oldState = _loopHeadState[node]; if (Join(ref oldState, ref this.State)) { _loopHeadState[node] = oldState; this.stateChangedAfterUse = true; } } /// <summary> /// Used to resolve break statements in each statement form that has a break statement /// (loops, switch). /// </summary> private void ResolveBreaks(TLocalState breakState, LabelSymbol label) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { Join(ref breakState, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } SetState(breakState); } /// <summary> /// Used to resolve continue statements in each statement form that supports it. /// </summary> private void ResolveContinues(LabelSymbol continueLabel) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == continueLabel) { // Technically, nothing in the language specification depends on the state // at the continue label, so we could just discard them instead of merging // the states. In fact, we need not have added continue statements to the // pending jump queue in the first place if we were interested solely in the // flow analysis. However, region analysis (in support of extract method) // and other forms of more precise analysis // depend on continue statements appearing in the pending branch queue, so // we process them from the queue here. Join(ref this.State, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } } /// <summary> /// Subclasses override this if they want to take special actions on processing a goto /// statement, when both the jump and the label have been located. /// </summary> protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target) { target.AssertIsLabeledStatement(); } /// <summary> /// To handle a label, we resolve all branches to that label. Returns true if the state of /// the label changes as a result. /// </summary> /// <param name="label">Target label</param> /// <param name="target">Statement containing the target label</param> private bool ResolveBranches(LabelSymbol label, BoundStatement target) { target?.AssertIsLabeledStatementWithLabel(label); bool labelStateChanged = false; var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { ResolveBranch(pending, label, target, ref labelStateChanged); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } return labelStateChanged; } protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged) { var state = LabelState(label); if (target != null) { NoteBranch(pending, pending.Branch, target); } var changed = Join(ref state, ref pending.State); if (changed) { labelStateChanged = true; _labels[label] = state; } } protected struct SavedPending { public readonly ArrayBuilder<PendingBranch> PendingBranches; public readonly PooledHashSet<BoundStatement> LabelsSeen; public SavedPending(ArrayBuilder<PendingBranch> pendingBranches, PooledHashSet<BoundStatement> labelsSeen) { this.PendingBranches = pendingBranches; this.LabelsSeen = labelsSeen; } } /// <summary> /// Since branches cannot branch into constructs, only out, we save the pending branches /// when visiting more nested constructs. When tracking exceptions, we store the current /// state as the exception state for the following code. /// </summary> protected SavedPending SavePending() { Debug.Assert(!this.IsConditionalState); var result = new SavedPending(PendingBranches, _labelsSeen); PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); return result; } /// <summary> /// We use this when closing a block that may contain labels or branches /// - branches to new labels are resolved /// - new labels are removed (no longer can be reached) /// - unresolved pending branches are carried forward /// </summary> /// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param> protected void RestorePending(SavedPending oldPending) { foreach (var node in _labelsSeen) { switch (node.Kind) { case BoundKind.LabeledStatement: { var label = (BoundLabeledStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.LabelStatement: { var label = (BoundLabelStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.SwitchSection: { var sec = (BoundSwitchSection)node; foreach (var label in sec.SwitchLabels) { stateChangedAfterUse |= ResolveBranches(label.Label, sec); } } break; default: // there are no other kinds of labels throw ExceptionUtilities.UnexpectedValue(node.Kind); } } oldPending.PendingBranches.AddRange(this.PendingBranches); PendingBranches.Free(); PendingBranches = oldPending.PendingBranches; // We only use SavePending/RestorePending when there could be no branch into the region between them. // So there is no need to save the labels seen between the calls. If there were such a need, we would // do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment _labelsSeen.Free(); _labelsSeen = oldPending.LabelsSeen; } #region visitors /// <summary> /// Since each language construct must be handled according to the rules of the language specification, /// the default visitor reports that the construct for the node is not implemented in the compiler. /// </summary> public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?"); Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location); return null; } public override BoundNode VisitAttribute(BoundAttribute node) { // No flow analysis is ever done in attributes (or their arguments). return null; } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { VisitRvalue(node.Expression); SetUnreachable(); return node; } public override BoundNode VisitPassByCopy(BoundPassByCopy node) { VisitRvalue(node.Expression); return node; } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); bool negated = node.Pattern.IsNegated(out var pattern); Debug.Assert(negated == node.IsNegated); if (VisitPossibleConditionalAccess(node.Expression, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(patternMatchesNull(pattern) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } else if (IsConditionalState) { // Patterns which only match a single boolean value should propagate conditional state // for example, `(a != null && a.M(out x)) is true` should have the same conditional state as `(a != null && a.M(out x))`. if (isBoolTest(pattern) is bool value) { if (!value) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { // Patterns which match more than a single boolean value cannot propagate conditional state // for example, `(a != null && a.M(out x)) is bool b` should not have conditional state Unsplit(); } } VisitPattern(pattern); var reachableLabels = node.DecisionDag.ReachableLabels; if (!reachableLabels.Contains(node.WhenTrueLabel)) { SetState(this.StateWhenFalse); SetConditionalState(UnreachableState(), this.State); } else if (!reachableLabels.Contains(node.WhenFalseLabel)) { SetState(this.StateWhenTrue); SetConditionalState(this.State, UnreachableState()); } if (negated) { SetConditionalState(this.StateWhenFalse, this.StateWhenTrue); } return node; static bool patternMatchesNull(BoundPattern pattern) { switch (pattern) { case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern { IsVar: false }: case BoundConstantPattern { ConstantValue: { IsNull: false } }: return false; case BoundConstantPattern { ConstantValue: { IsNull: true } }: return true; case BoundNegatedPattern negated: return !patternMatchesNull(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `a?.b(out x) is null or C` // pattern matches null if either subpattern matches null var leftNullTest = patternMatchesNull(binary.Left); return patternMatchesNull(binary.Left) || patternMatchesNull(binary.Right); } // `a?.b out x is not null and var c` // pattern matches null only if both subpatterns match null return patternMatchesNull(binary.Left) && patternMatchesNull(binary.Right); case BoundDeclarationPattern { IsVar: true }: case BoundDiscardPattern: return true; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } // Returns `true` if the pattern only matches a `true` input. // Returns `false` if the pattern only matches a `false` input. // Otherwise, returns `null`. static bool? isBoolTest(BoundPattern pattern) { switch (pattern) { case BoundConstantPattern { ConstantValue: { IsBoolean: true, BooleanValue: var boolValue } }: return boolValue; case BoundNegatedPattern negated: return !isBoolTest(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `(a != null && a.b(out x)) is true or true` matches `true` // `(a != null && a.b(out x)) is true or false` matches any boolean // both subpatterns must have the same bool test for the test to propagate out var leftNullTest = isBoolTest(binary.Left); return leftNullTest is null ? null : leftNullTest != isBoolTest(binary.Right) ? null : leftNullTest; } // `(a != null && a.b(out x)) is true and true` matches `true` // `(a != null && a.b(out x)) is true and var x` matches `true` // `(a != null && a.b(out x)) is true and false` never matches and is a compile error return isBoolTest(binary.Left) ?? isBoolTest(binary.Right); case BoundConstantPattern { ConstantValue: { IsBoolean: false } }: case BoundDiscardPattern: case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern: return null; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } } public virtual void VisitPattern(BoundPattern pattern) { Split(); } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { // All patterns are handled by VisitPattern throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { return VisitTupleExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { return VisitTupleExpression(node); } private BoundNode VisitTupleExpression(BoundTupleExpression node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), null); return null; } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { VisitRvalue(node.Left); VisitRvalue(node.Right); return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { VisitRvalue(node.Receiver); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { VisitRvalue(node.Receiver); return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { VisitRvalue(node.Expression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } #nullable enable protected BoundNode? VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data) { // If there can be any branching, then we need to treat the expressions // as optionally evaluated. Otherwise, we treat them as always evaluated (BoundExpression? construction, bool useBoolReturns, bool firstPartIsConditional) = data switch { null => (null, false, false), { } d => (d.Construction, d.UsesBoolReturns, d.HasTrailingHandlerValidityParameter) }; VisitRvalue(construction); bool hasConditionalEvaluation = useBoolReturns || firstPartIsConditional; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; _ = VisitInterpolatedStringHandlerParts(node, useBoolReturns, firstPartIsConditional, ref shortCircuitState); if (hasConditionalEvaluation) { Debug.Assert(shortCircuitState != null); Join(ref this.State, ref shortCircuitState); } return null; } #nullable disable public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { return VisitInterpolatedStringBase(node, node.InterpolationData); } public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // If the node is unconverted, we'll just treat it as if the contents are always evaluated return VisitInterpolatedStringBase(node, data: null); } public override BoundNode VisitStringInsert(BoundStringInsert node) { VisitRvalue(node.Value); if (node.Alignment != null) { VisitRvalue(node.Alignment); } if (node.Format != null) { VisitRvalue(node.Format); } return null; } public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { return null; } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { return null; } public override BoundNode VisitArgList(BoundArgList node) { // The "__arglist" expression that is legal inside a varargs method has no // effect on flow analysis and it has no children. return null; } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { // When we have M(__arglist(x, y, z)) we must visit x, y and z. VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { // Note that we require that the variable whose reference we are taking // has been initialized; it is similar to passing the variable as a ref parameter. VisitRvalue(node.Operand, isKnownToBeAnLvalue: true); return null; } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) { VisitStatement(node.Statement); return null; } public override BoundNode VisitLambda(BoundLambda node) => null; public override BoundNode VisitLocal(BoundLocal node) { SplitIfBooleanConstant(node); return null; } public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) { if (node.InitializerOpt != null) { // analyze the expression VisitRvalue(node.InitializerOpt, isKnownToBeAnLvalue: node.LocalSymbol.RefKind != RefKind.None); // byref assignment is also a potential write if (node.LocalSymbol.RefKind != RefKind.None) { WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, method: null); } } return null; } public override BoundNode VisitBlock(BoundBlock node) { VisitStatements(node.Statements); return null; } private void VisitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { VisitStatement(statement); } } public override BoundNode VisitScope(BoundScope node) { VisitStatements(node.Statements); return null; } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitCall(BoundCall node) { // If the method being called is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // definite assignment analysis. bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree); TLocalState savedState = default(TLocalState); if (callsAreOmitted) { savedState = this.State.Clone(); SetUnreachable(); } VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); VisitArgumentsBeforeCall(node.Arguments, node.ArgumentRefKindsOpt); if (node.Method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: true); } VisitArgumentsAfterCall(node.Arguments, node.ArgumentRefKindsOpt, node.Method); VisitReceiverAfterCall(node.ReceiverOpt, node.Method); if (callsAreOmitted) { this.State = savedState; } return null; } protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall) { var localFuncState = GetOrCreateLocalFuncUsages(symbol); VisitLocalFunctionUse(symbol, localFuncState, syntax, isCall); } protected virtual void VisitLocalFunctionUse( LocalFunctionSymbol symbol, TLocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { if (isCall) { Join(ref State, ref localFunctionState.StateFromBottom); Meet(ref State, ref localFunctionState.StateFromTop); } localFunctionState.Visited = true; } private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method) { if (method is null || method.MethodKind != MethodKind.Constructor) { VisitRvalue(receiverOpt); } } private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method) { if (receiverOpt is null) { return; } if (method is null) { WriteArgument(receiverOpt, RefKind.Ref, method: null); } else if (method.TryGetThisParameter(out var thisParameter) && thisParameter is object && !TypeIsImmutable(thisParameter.Type)) { var thisRefKind = thisParameter.RefKind; if (thisRefKind.IsWritableReference()) { WriteArgument(receiverOpt, thisRefKind, method); } } } /// <summary> /// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on /// the type is known (by flow analysis) not to write the receiver. /// </summary> /// <param name="t"></param> /// <returns></returns> private static bool TypeIsImmutable(TypeSymbol t) { switch (t.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_DateTime: return true; default: return t.IsNullableType(); } } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var method = GetReadMethod(node.Indexer); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); if ((object)method != null) { VisitReceiverAfterCall(node.ReceiverOpt, method); } return null; } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { // Index or Range pattern indexers evaluate the following in order: // 1. The receiver // 1. The Count or Length method off the receiver // 2. The argument to the access // 3. The pattern method VisitRvalue(node.Receiver); var method = GetReadMethod(node.LengthOrCountProperty); VisitReceiverAfterCall(node.Receiver, method); VisitRvalue(node.Argument); method = node.PatternSymbol switch { PropertySymbol p => GetReadMethod(p), MethodSymbol m => m, _ => throw ExceptionUtilities.UnexpectedValue(node.PatternSymbol) }; VisitReceiverAfterCall(node.Receiver, method); return null; } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { VisitRvalue(node.ReceiverOpt); VisitRvalue(node.Argument); return null; } /// <summary> /// Do not call for a local function. /// </summary> protected virtual void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { Debug.Assert(method?.OriginalDefinition.MethodKind != MethodKind.LocalFunction); VisitArgumentsBeforeCall(arguments, refKindsOpt); VisitArgumentsAfterCall(arguments, refKindsOpt, method); } private void VisitArgumentsBeforeCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { // first value and ref parameters are read... for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); if (refKind != RefKind.Out) { VisitRvalue(arguments[i], isKnownToBeAnLvalue: refKind != RefKind.None); } else { VisitLvalue(arguments[i]); } } } /// <summary> /// Writes ref and out parameters /// </summary> private void VisitArgumentsAfterCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); // passing as a byref argument is also a potential write if (refKind != RefKind.None) { WriteArgument(arguments[i], refKind, method); } } } protected static RefKind GetRefKind(ImmutableArray<RefKind> refKindsOpt, int index) { return refKindsOpt.IsDefault || refKindsOpt.Length <= index ? RefKind.None : refKindsOpt[index]; } protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) { } public override BoundNode VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { VisitRvalue(child as BoundExpression); } return null; } public override BoundNode VisitBadStatement(BoundBadStatement node) { foreach (var child in node.ChildBoundNodes) { if (child is BoundStatement) { VisitStatement(child as BoundStatement); } else { VisitRvalue(child as BoundExpression); } } return null; } // Can be called as part of a bad expression. public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { foreach (var child in node.Initializers) { VisitRvalue(child); } return null; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { var methodGroup = node.Argument as BoundMethodGroup; if (methodGroup != null) { if ((object)node.MethodOpt != null && node.MethodOpt.RequiresInstanceReceiver) { EnterRegionIfNeeded(methodGroup); VisitRvalue(methodGroup.ReceiverOpt); LeaveRegionIfNeeded(methodGroup); } else if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { VisitRvalue(node.Argument); } return null; } public override BoundNode VisitTypeExpression(BoundTypeExpression node) { return null; } public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. return this.Visit(node.Data.ValueExpression); } public override BoundNode VisitLiteral(BoundLiteral node) { SplitIfBooleanConstant(node); return null; } protected void SplitIfBooleanConstant(BoundExpression node) { if (node.ConstantValue is { IsBoolean: true, BooleanValue: bool booleanValue }) { var unreachable = UnreachableState(); Split(); if (booleanValue) { StateWhenFalse = unreachable; } else { StateWhenTrue = unreachable; } } } public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node) { return null; } public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) { return null; } public override BoundNode VisitModuleVersionId(BoundModuleVersionId node) { return null; } public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node) { return null; } public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) { return null; } public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node) { return null; } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.MethodGroup) { if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver)) { BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt; // A method group's "implicit this" is only used for instance methods. EnterRegionIfNeeded(node.Operand); VisitRvalue(receiver); LeaveRegionIfNeeded(node.Operand); } else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { Visit(node.Operand); } return null; } public override BoundNode VisitIfStatement(BoundIfStatement node) { // 5.3.3.5 If statements VisitCondition(node.Condition); TLocalState trueState = StateWhenTrue; TLocalState falseState = StateWhenFalse; SetState(trueState); VisitStatement(node.Consequence); trueState = this.State; SetState(falseState); if (node.AlternativeOpt != null) { VisitStatement(node.AlternativeOpt); } Join(ref this.State, ref trueState); return null; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var oldPending = SavePending(); // we do not allow branches into a try statement var initialState = this.State.Clone(); // use this state to resolve all the branches introduced and internal to try/catch var pendingBeforeTry = SavePending(); VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref initialState); var finallyState = initialState.Clone(); var endState = this.State; foreach (var catchBlock in node.CatchBlocks) { SetState(initialState.Clone()); VisitCatchBlockWithAnyTransferFunction(catchBlock, ref finallyState); Join(ref endState, ref this.State); } // Give a chance to branches internal to try/catch to resolve. // Carry forward unresolved branches. RestorePending(pendingBeforeTry); // NOTE: At this point all branches that are internal to try or catch blocks have been resolved. // However we have not yet restored the oldPending branches. Therefore all the branches // that are currently pending must have been introduced in try/catch and do not terminate inside those blocks. // // With exception of YieldReturn, these branches logically go through finally, if such present, // so we must Union/Intersect finally state as appropriate if (node.FinallyBlockOpt != null) { // branches from the finally block, while illegal, should still not be considered // to execute the finally block before occurring. Also, we do not handle branches // *into* the finally block. SetState(finallyState); // capture tryAndCatchPending before going into finally // we will need pending branches as they were before finally later var tryAndCatchPending = SavePending(); var stateMovedUpInFinally = ReachableBottomState(); VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUpInFinally); foreach (var pend in tryAndCatchPending.PendingBranches) { if (pend.Branch == null) { continue; // a tracked exception } if (pend.Branch.Kind != BoundKind.YieldReturnStatement) { updatePendingBranchState(ref pend.State, ref stateMovedUpInFinally); if (pend.IsConditionalState) { updatePendingBranchState(ref pend.StateWhenTrue, ref stateMovedUpInFinally); updatePendingBranchState(ref pend.StateWhenFalse, ref stateMovedUpInFinally); } } } RestorePending(tryAndCatchPending); Meet(ref endState, ref this.State); if (_nonMonotonicTransfer) { Join(ref endState, ref stateMovedUpInFinally); } } SetState(endState); RestorePending(oldPending); return null; void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally) { Meet(ref stateToUpdate, ref this.State); if (_nonMonotonicTransfer) { Join(ref stateToUpdate, ref stateMovedUpInFinally); } } } protected Optional<TLocalState> NonMonotonicState; /// <summary> /// Join state from other try block, potentially in a nested method. /// </summary> protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other) { Join(ref self, ref other); } private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitTryBlock(tryBlock, node, ref tryState); var tempTryStateValue = NonMonotonicState.Value; Join(ref tryState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitTryBlock(tryBlock, node, ref tryState); } } protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { VisitStatement(tryBlock); } private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitCatchBlock(catchBlock, ref finallyState); var tempTryStateValue = NonMonotonicState.Value; Join(ref finallyState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitCatchBlock(catchBlock, ref finallyState); } } protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (catchBlock.ExceptionSourceOpt != null) { VisitLvalue(catchBlock.ExceptionSourceOpt); } if (catchBlock.ExceptionFilterPrologueOpt is { }) { VisitStatementList(catchBlock.ExceptionFilterPrologueOpt); } if (catchBlock.ExceptionFilterOpt != null) { VisitCondition(catchBlock.ExceptionFilterOpt); SetState(StateWhenTrue); } VisitStatement(catchBlock.Body); } private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitFinallyBlock(finallyBlock, ref stateMovedUp); var tempTryStateValue = NonMonotonicState.Value; Join(ref stateMovedUp, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitFinallyBlock(finallyBlock, ref stateMovedUp); } } protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { VisitStatement(finallyBlock); // this should generate no pending branches } public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) { return VisitBlock(node.FinallyBlock); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { var result = VisitReturnStatementNoAdjust(node); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return result; } protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node) { VisitRvalue(node.ExpressionOpt, isKnownToBeAnLvalue: node.RefKind != RefKind.None); // byref return is also a potential write if (node.RefKind != RefKind.None) { WriteArgument(node.ExpressionOpt, node.RefKind, method: null); } return null; } public override BoundNode VisitThisReference(BoundThisReference node) { return null; } public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { return null; } public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { return null; } public override BoundNode VisitParameter(BoundParameter node) { return null; } protected virtual void VisitLvalueParameter(BoundParameter node) { } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNewT(BoundNewT node) { VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitRvalue(node.InitializerExpressionOpt); return null; } // represents anything that occurs at the invocation of the property setter protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null) { VisitReceiverAfterCall(receiver, setter); } // returns false if expression is not a property access // or if the property has a backing field // and accessed in a corresponding constructor private bool RegularPropertyAccess(BoundExpression expr) { if (expr.Kind != BoundKind.PropertyAccess) { return false; } return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var method = GetWriteMethod(property); VisitReceiverBeforeCall(left.ReceiverOpt, method); VisitRvalue(node.Right); PropertySetter(node, left.ReceiverOpt, method, node.Right); return null; } } VisitLvalue(node.Left); VisitRvalue(node.Right, isKnownToBeAnLvalue: node.IsRef); // byref assignment is also a potential write if (node.IsRef) { // Assume that BadExpression is a ref location to avoid // cascading diagnostics var refKind = node.Left.Kind == BoundKind.BadExpression ? RefKind.Ref : node.Left.GetRefKind(); WriteArgument(node.Right, refKind, method: null); } return null; } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { VisitLvalue(node.Left); VisitRvalue(node.Right); return null; } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { VisitCompoundAssignmentTarget(node); VisitRvalue(node.Right); AfterRightHasBeenVisited(node); return null; } protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)GetWriteMethod(property)); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); return; } } VisitRvalue(node.Left, isKnownToBeAnLvalue: true); } protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node) { if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var writeMethod = GetWriteMethod(property); PropertySetter(node, left.ReceiverOpt, writeMethod); VisitReceiverAfterCall(left.ReceiverOpt, writeMethod); return; } } } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); return null; } private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { bool asLvalue = (object)fieldSymbol != null && (fieldSymbol.IsFixedSizeBuffer || !fieldSymbol.IsStatic && fieldSymbol.ContainingType.TypeKind == TypeKind.Struct && receiverOpt != null && receiverOpt.Kind != BoundKind.TypeExpression && (object)receiverOpt.Type != null && !receiverOpt.Type.IsPrimitiveRecursiveStruct()); if (asLvalue) { VisitLvalue(receiverOpt); } else { VisitRvalue(receiverOpt); } } public override BoundNode VisitFieldInfo(BoundFieldInfo node) { return null; } public override BoundNode VisitMethodInfo(BoundMethodInfo node) { return null; } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol)) { var backingField = (property as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(node.ReceiverOpt, backingField); return null; } } var method = GetReadMethod(property); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitReceiverAfterCall(node.ReceiverOpt, method); return null; // TODO: In an expression such as // M().Prop = G(); // Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor // occur after both. The precise abstract flow pass does not yet currently have this quite right. // Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read) // which should assume that the receiver will have been handled by the caller. This can be invoked // twice for read/write operations such as // M().Prop += 1 // or at the appropriate place in the sequence for read or write operations. // Do events require any special handling too? } public override BoundNode VisitEventAccess(BoundEventAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return null; } public override BoundNode VisitQueryClause(BoundQueryClause node) { VisitRvalue(node.UnoptimizedForm ?? node.Value); return null; } private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { foreach (var v in node.LocalDeclarations) { Visit(v); } return null; } public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitWhileStatement(BoundWhileStatement node) { // while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel: LoopHead(node); VisitCondition(node.Condition); TLocalState bodyState = StateWhenTrue; TLocalState breakState = StateWhenFalse; SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitWithExpression(BoundWithExpression node) { VisitRvalue(node.Receiver); VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers); return null; } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { VisitRvalue(node.Expression); foreach (var i in node.Indices) { VisitRvalue(i); } return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { if (node.OperatorKind.IsLogical()) { Debug.Assert(!node.OperatorKind.IsUserDefined()); VisitBinaryLogicalOperatorChildren(node); } else if (node.InterpolatedStringHandlerData is { } data) { VisitBinaryInterpolatedStringAddition(node); } else { VisitBinaryOperatorChildren(node); } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { VisitBinaryLogicalOperatorChildren(node); return null; } private void VisitBinaryLogicalOperatorChildren(BoundExpression node) { // Do not blow the stack due to a deep recursion on the left. var stack = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression binary; BoundExpression child = node; while (true) { var childKind = child.Kind; if (childKind == BoundKind.BinaryOperator) { var binOp = (BoundBinaryOperator)child; if (!binOp.OperatorKind.IsLogical()) { break; } Debug.Assert(!binOp.OperatorKind.IsUserDefined()); binary = child; child = binOp.Left; } else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator) { binary = child; child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left; } else { break; } stack.Push(binary); } Debug.Assert(stack.Count > 0); VisitCondition(child); while (true) { binary = stack.Pop(); BinaryOperatorKind kind; BoundExpression right; switch (binary.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)binary; kind = binOp.OperatorKind; right = binOp.Right; break; case BoundKind.UserDefinedConditionalLogicalOperator: var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary; kind = udBinOp.OperatorKind; right = udBinOp.Right; break; default: throw ExceptionUtilities.UnexpectedValue(binary.Kind); } var op = kind.Operator(); var isAnd = op == BinaryOperatorKind.And; var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; Debug.Assert(isAnd || op == BinaryOperatorKind.Or); var leftTrue = this.StateWhenTrue; var leftFalse = this.StateWhenFalse; SetState(isAnd ? leftTrue : leftFalse); AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); if (stack.Count == 0) { break; } AdjustConditionalState(binary); } Debug.Assert((object)binary == node); stack.Free(); } protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { Visit(right); // First part of VisitCondition AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); } protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { AdjustConditionalState(right); // Second part of VisitCondition if (!isBool) { this.Unsplit(); this.Split(); } var resultTrue = this.StateWhenTrue; var resultFalse = this.StateWhenFalse; if (isAnd) { Join(ref resultFalse, ref leftFalse); } else { Join(ref resultTrue, ref leftTrue); } SetConditionalState(resultTrue, resultFalse); if (!isBool) { this.Unsplit(); } } private void VisitBinaryOperatorChildren(BoundBinaryOperator node) { // It is common in machine-generated code for there to be deep recursion on the left side of a binary // operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left // hand side. To mitigate the risk of stack overflow we use an explicit stack. // // Of course we must ensure that we visit the left hand side before the right hand side. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); BoundBinaryOperator binary = node; do { stack.Push(binary); binary = binary.Left as BoundBinaryOperator; } while (binary != null && !binary.OperatorKind.IsLogical() && binary.InterpolatedStringHandlerData is null); VisitBinaryOperatorChildren(stack); stack.Free(); } #nullable enable protected virtual void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(binary.Left, out var stateWhenNotNull) && canLearnFromOperator(binary) && isKnownNullOrNotNull(binary.Right)) { if (_nonMonotonicTransfer) { // In this very specific scenario, we need to do extra work to track unassignments for region analysis. // See `AbstractFlowPass.VisitCatchBlockWithAnyTransferFunction` for a similar scenario in catch blocks. Optional<TLocalState> oldState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitRvalue(binary.Right); var tempStateValue = NonMonotonicState.Value; Join(ref stateWhenNotNull, ref tempStateValue); if (oldState.HasValue) { var oldStateValue = oldState.Value; Join(ref oldStateValue, ref tempStateValue); oldState = oldStateValue; } NonMonotonicState = oldState; } else { VisitRvalue(binary.Right); Meet(ref stateWhenNotNull, ref State); } var isNullConstant = binary.Right.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); if (stack.Count == 0) { return; } binary = stack.Pop(); } while (true) { if (!canLearnFromOperator(binary) || !learnFromOperator(binary)) { Unsplit(); VisitRvalue(binary.Right); } if (stack.Count == 0) { break; } binary = stack.Pop(); } static bool canLearnFromOperator(BoundBinaryOperator binary) { var kind = binary.OperatorKind; return kind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual && (!kind.IsUserDefined() || kind.IsLifted()); } static bool isKnownNullOrNotNull(BoundExpression expr) { return expr.ConstantValue is object || (expr is BoundConversion { ConversionKind: ConversionKind.ExplicitNullable or ConversionKind.ImplicitNullable } conv && conv.Operand.Type!.IsNonNullableValueType()); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; // Returns true if `binary.Right` was visited by the call. bool learnFromOperator(BoundBinaryOperator binary) { // `true == a?.b(out x)` if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out var stateWhenNotNull)) { var isNullConstant = binary.Left.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // `a && b(out x) == true` else if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); return true; } // `true == a && b(out x)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } return true; } return false; } } protected void VisitBinaryInterpolatedStringAddition(BoundBinaryOperator node) { Debug.Assert(node.InterpolatedStringHandlerData.HasValue); var stack = ArrayBuilder<BoundInterpolatedString>.GetInstance(); var data = node.InterpolatedStringHandlerData.GetValueOrDefault(); while (PushBinaryOperatorInterpolatedStringChildren(node, stack) is { } next) { node = next; } Debug.Assert(stack.Count >= 2); VisitRvalue(data.Construction); bool visitedFirst = false; bool hasTrailingHandlerValidityParameter = data.HasTrailingHandlerValidityParameter; bool hasConditionalEvaluation = data.UsesBoolReturns || hasTrailingHandlerValidityParameter; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; while (stack.TryPop(out var currentString)) { visitedFirst |= VisitInterpolatedStringHandlerParts(currentString, data.UsesBoolReturns, firstPartIsConditional: visitedFirst || hasTrailingHandlerValidityParameter, ref shortCircuitState); } if (hasConditionalEvaluation) { Join(ref State, ref shortCircuitState); } stack.Free(); } protected virtual BoundBinaryOperator? PushBinaryOperatorInterpolatedStringChildren(BoundBinaryOperator node, ArrayBuilder<BoundInterpolatedString> stack) { stack.Push((BoundInterpolatedString)node.Right); switch (node.Left) { case BoundBinaryOperator next: return next; case BoundInterpolatedString @string: stack.Push(@string); return null; default: throw ExceptionUtilities.UnexpectedValue(node.Left.Kind); } } protected virtual bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref TLocalState? shortCircuitState) { Debug.Assert(shortCircuitState != null || (!usesBoolReturns && !firstPartIsConditional)); if (node.Parts.IsEmpty) { return false; } ReadOnlySpan<BoundExpression> parts; if (firstPartIsConditional) { parts = node.Parts.AsSpan(); } else { VisitRvalue(node.Parts[0]); shortCircuitState = State.Clone(); parts = node.Parts.AsSpan()[1..]; } foreach (var part in parts) { VisitRvalue(part); if (usesBoolReturns) { Debug.Assert(shortCircuitState != null); Join(ref shortCircuitState, ref State); } } return true; } #nullable disable public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { // We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26) VisitCondition(node.Operand); // it inverts the sense of assignedWhenTrue and assignedWhenFalse. SetConditionalState(StateWhenFalse, StateWhenTrue); } else { VisitRvalue(node.Operand); } return null; } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (node.LeftOperandOpt != null) { VisitRvalue(node.LeftOperandOpt); } if (node.RightOperandOpt != null) { VisitRvalue(node.RightOperandOpt); } return null; } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { // TODO: should we also specially handle events? if (RegularPropertyAccess(node.Operand)) { var left = (BoundPropertyAccess)node.Operand; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); var writeMethod = GetWriteMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write return null; } } VisitRvalue(node.Operand); return null; } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } if (node.InitializerOpt != null) { VisitArrayInitializationInternal(node, node.InitializerOpt); } return null; } private void VisitArrayInitializationInternal(BoundArrayCreation arrayCreation, BoundArrayInitialization node) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { VisitArrayInitializationInternal(arrayCreation, (BoundArrayInitialization)child); } else { VisitRvalue(child); } } } public override BoundNode VisitForStatement(BoundForStatement node) { if (node.Initializer != null) { VisitStatement(node.Initializer); } LoopHead(node); TLocalState bodyState, breakState; if (node.Condition != null) { VisitCondition(node.Condition); bodyState = this.StateWhenTrue; breakState = this.StateWhenFalse; } else { bodyState = this.State; breakState = UnreachableState(); } SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); if (node.Increment != null) { VisitStatement(node.Increment); } LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitForEachStatement(BoundForEachStatement node) { // foreach [await] ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel: VisitForEachExpression(node); var breakState = this.State.Clone(); LoopHead(node); VisitForEachIterationVariables(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)node.Syntax).AwaitKeyword != default) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } protected virtual void VisitForEachExpression(BoundForEachStatement node) { VisitRvalue(node.Expression); } public virtual void VisitForEachIterationVariables(BoundForEachStatement node) { } public override BoundNode VisitAsOperator(BoundAsOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitIsOperator(BoundIsOperator node) { if (VisitPossibleConditionalAccess(node.Operand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(stateWhenNotNull, State); } else { // `(a && b.M(out x)) is bool` should discard conditional state from LHS Unsplit(); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { if (node.ReceiverOpt != null) { // An explicit or implicit receiver, for example in an expression such as (x.Goo is Action, or Goo is Action), is considered to be read. VisitRvalue(node.ReceiverOpt); } return null; } #nullable enable public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (IsConstantNull(node.LeftOperand)) { VisitRvalue(node.LeftOperand); Visit(node.RightOperand); } else { TLocalState savedState; if (VisitPossibleConditionalAccess(node.LeftOperand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); savedState = stateWhenNotNull; } else { Unsplit(); savedState = State.Clone(); } if (node.LeftOperand.ConstantValue != null) { SetUnreachable(); } Visit(node.RightOperand); if (IsConditionalState) { Join(ref StateWhenTrue, ref savedState); Join(ref StateWhenFalse, ref savedState); } else { Join(ref this.State, ref savedState); } } return null; } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { var access = node switch { BoundConditionalAccess ca => ca, BoundConversion { Conversion: Conversion conversion, Operand: BoundConditionalAccess ca } when CanPropagateStateWhenNotNull(conversion) => ca, _ => null }; if (access is not null) { EnterRegionIfNeeded(access); Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); Debug.Assert(!IsConditionalState); LeaveRegionIfNeeded(access); return true; } stateWhenNotNull = default; return false; } /// <summary> /// "State when not null" can only propagate out of a conditional access if /// it is not subject to a user-defined conversion whose parameter is not of a non-nullable value type. /// </summary> protected static bool CanPropagateStateWhenNotNull(Conversion conversion) { if (!conversion.IsValid) { return false; } if (!conversion.IsUserDefined) { return true; } var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount is 1); var param = method.Parameters[0]; return param.Type.IsNonNullableValueType(); } /// <summary> /// Unconditionally visits an expression. /// If the expression has "state when not null" after visiting, /// the method returns 'true' and writes the state to <paramref name="stateWhenNotNull" />. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } else { Visit(node); return false; } } private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull) { // The receiver may also be a conditional access. // `(a?.b(x = 1))?.c(y = 1)` if (VisitPossibleConditionalAccess(node.Receiver, out var receiverStateWhenNotNull)) { stateWhenNotNull = receiverStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver)) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull if (VisitPossibleConditionalAccess(node.AccessExpression, out var firstAccessStateWhenNotNull)) { stateWhenNotNull = firstAccessStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } } else { var savedState = this.State.Clone(); if (IsConstantNull(node.Receiver)) { SetUnreachable(); } else { SetState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. VisitRvalue(innerCondAccess.Receiver); expr = innerCondAccess.AccessExpression; // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); } Debug.Assert(expr is BoundExpression); VisitRvalue(expr); stateWhenNotNull = State; State = savedState; Join(ref State, ref stateWhenNotNull); } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, stateWhenNotNull: out _); return null; } #nullable disable public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { VisitRvalue(node.Receiver); var savedState = this.State.Clone(); VisitRvalue(node.WhenNotNull); Join(ref this.State, ref savedState); if (node.WhenNullOpt != null) { savedState = this.State.Clone(); VisitRvalue(node.WhenNullOpt); Join(ref this.State, ref savedState); } return null; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { return null; } public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) { var savedState = this.State.Clone(); VisitRvalue(node.ValueTypeReceiver); Join(ref this.State, ref savedState); savedState = this.State.Clone(); VisitRvalue(node.ReferenceTypeReceiver); Join(ref this.State, ref savedState); return null; } public override BoundNode VisitSequence(BoundSequence node) { var sideEffects = node.SideEffects; if (!sideEffects.IsEmpty) { foreach (var se in sideEffects) { VisitRvalue(se); } } VisitRvalue(node.Value); return null; } public override BoundNode VisitSequencePoint(BoundSequencePoint node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitStatementList(BoundStatementList node) { return VisitStatementListWorker(node); } private BoundNode VisitStatementListWorker(BoundStatementList node) { foreach (var statement in node.Statements) { VisitStatement(statement); } return null; } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { return VisitStatementListWorker(node); } public override BoundNode VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. return VisitLambda(node.BindForErrorRecovery()); } public override BoundNode VisitBreakStatement(BoundBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitContinueStatement(BoundContinueStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) { return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative); } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative); } #nullable enable protected virtual BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isByRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; if (IsConstantTrue(condition)) { VisitConditionalOperand(alternativeState, alternative, isByRef); VisitConditionalOperand(consequenceState, consequence, isByRef); } else if (IsConstantFalse(condition)) { VisitConditionalOperand(consequenceState, consequence, isByRef); VisitConditionalOperand(alternativeState, alternative, isByRef); } else { // at this point, the state is conditional after a conditional expression if: // 1. the state is conditional after the consequence, or // 2. the state is conditional after the alternative VisitConditionalOperand(consequenceState, consequence, isByRef); var conditionalAfterConsequence = IsConditionalState; var (afterConsequenceWhenTrue, afterConsequenceWhenFalse) = conditionalAfterConsequence ? (StateWhenTrue, StateWhenFalse) : (State, State); VisitConditionalOperand(alternativeState, alternative, isByRef); if (!conditionalAfterConsequence && !IsConditionalState) { // simplify in the common case Join(ref this.State, ref afterConsequenceWhenTrue); } else { Split(); Join(ref this.StateWhenTrue, ref afterConsequenceWhenTrue); Join(ref this.StateWhenFalse, ref afterConsequenceWhenFalse); } } return null; } #nullable disable private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef) { SetState(state); if (isByRef) { VisitLvalue(operand); // exposing ref is a potential write WriteArgument(operand, RefKind.Ref, method: null); } else { Visit(operand); } } public override BoundNode VisitBaseReference(BoundBaseReference node) { return null; } public override BoundNode VisitDoStatement(BoundDoStatement node) { // do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel: LoopHead(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); VisitCondition(node.Condition); TLocalState breakState = this.StateWhenFalse; SetState(this.StateWhenTrue); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } protected void VisitLabel(LabelSymbol label, BoundStatement node) { node.AssertIsLabeledStatementWithLabel(label); ResolveBranches(label, node); var state = LabelState(label); Join(ref this.State, ref state); _labels[label] = this.State.Clone(); _labelsSeen.Add(node); } protected virtual void VisitLabel(BoundLabeledStatement node) { VisitLabel(node.Label, node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { VisitLabel(node.Label, node); return null; } public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) { VisitLabel(node); VisitStatement(node.Body); return null; } public override BoundNode VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) { return null; } public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node) { return null; } public override BoundNode VisitUsingStatement(BoundUsingStatement node) { if (node.ExpressionOpt != null) { VisitRvalue(node.ExpressionOpt); } if (node.DeclarationsOpt != null) { VisitStatement(node.DeclarationsOpt); } VisitStatement(node.Body); if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; } public override BoundNode VisitFixedStatement(BoundFixedStatement node) { VisitStatement(node.Declarations); VisitStatement(node.Body); return null; } public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundExpression expr = node.ExpressionOpt; VisitRvalue(expr); SetUnreachable(); return null; } public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, null)); SetUnreachable(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { return null; } public override BoundNode VisitDefaultExpression(BoundDefaultExpression node) { return null; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { VisitTypeExpression(node.SourceType); return null; } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { var savedState = this.State; SetState(UnreachableState()); Visit(node.Argument); SetState(savedState); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { VisitAddressOfOperand(node.Operand, shouldReadOperand: false); return null; } protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand) { if (shouldReadOperand) { this.VisitRvalue(operand); } else { this.VisitLvalue(operand); } this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned. } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { VisitRvalue(node.Expression); VisitRvalue(node.Index); return null; } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { return null; } private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) { VisitRvalue(node.Count); if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault) { foreach (var element in node.InitializerOpt.Initializers) { VisitRvalue(element); } } return null; } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // visit arguments as r-values VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor); return null; } public override BoundNode VisitArrayLength(BoundArrayLength node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { VisitCondition(node.Condition); Debug.Assert(this.IsConditionalState); if (node.JumpIfTrue) { PendingBranches.Add(new PendingBranch(node, this.StateWhenTrue, node.Label)); this.SetState(this.StateWhenFalse); } else { PendingBranches.Add(new PendingBranch(node, this.StateWhenFalse, node.Label)); this.SetState(this.StateWhenTrue); } return null; } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers) { foreach (var initializer in initializers) { VisitRvalue(initializer); } return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { var arguments = node.Arguments; if (!arguments.IsDefaultOrEmpty) { MethodSymbol method = null; if (node.MemberSymbol?.Kind == SymbolKind.Property) { var property = (PropertySymbol)node.MemberSymbol; method = GetReadMethod(property); } VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); } return null; } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { return null; } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (node.AddMethod.CallsAreOmitted(node.SyntaxTree)) { // If the underlying add method is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // flow analysis. TLocalState savedState = savedState = this.State.Clone(); SetUnreachable(); VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); this.State = savedState; } else { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); } return null; } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null); return null; } public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node) { return null; } public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return null; } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { return null; } public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { return null; } public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDiscardExpression(BoundDiscardExpression node) { return null; } private static MethodSymbol GetReadMethod(PropertySymbol property) => property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; private static MethodSymbol GetWriteMethod(PropertySymbol property) => property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node) { Visit(node.Initializer); VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) { VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { TLocalState leftState; if (RegularPropertyAccess(node.LeftOperand) && (BoundPropertyAccess)node.LeftOperand is var left && left.PropertySymbol is var property && property.RefKind == RefKind.None) { var readMethod = property.GetOwnOrInheritedGetMethod(); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, left); } else { VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt: null); } Join(ref this.State, ref leftState); return null; } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { Visit(node.InvokedExpression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature); return null; } public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) { // This is not encountered in correct programs, but can be seen if the function pointer was // unable to be converted and the semantic model is used to query for information. Visit(node.Operand); return null; } /// <summary> /// This visitor represents just the assignment part of the null coalescing assignment /// operator. /// </summary> protected virtual void VisitAssignmentOfNullCoalescingAssignment( BoundNullCoalescingAssignmentOperator node, BoundPropertyAccess propertyAccessOpt) { VisitRvalue(node.RightOperand); if (propertyAccessOpt != null) { var symbol = propertyAccessOpt.PropertySymbol; var writeMethod = symbol.GetOwnOrInheritedSetMethod(); PropertySetter(node, propertyAccessOpt.ReceiverOpt, writeMethod); } } public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) { return null; } public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) { return null; } public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) { return null; } /// <summary> /// This visitor represents just the non-assignment part of the null coalescing assignment /// operator (when the left operand is non-null). /// </summary> protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node) { } private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody) { if (blockBody == null) { Visit(expressionBody); return; } else if (expressionBody == null) { Visit(blockBody); return; } // In error cases we have two bodies. These are two unrelated pieces of code, // they are not executed one after another. As we don't really know which one the developer // intended to use, we need to visit both. We are going to pretend that there is // an unconditional fork in execution and then we are converging after each body is executed. // For example, if only one body assigns an out parameter, then after visiting both bodies // we should consider that parameter is not definitely assigned. // Note, that today this code is not executed for regular definite assignment analysis. It is // only executed for region analysis. TLocalState initialState = this.State.Clone(); Visit(blockBody); TLocalState afterBlock = this.State; SetState(initialState); Visit(expressionBody); Join(ref this.State, ref afterBlock); } #endregion visitors } /// <summary> /// The possible places that we are processing when there is a region. /// </summary> /// <remarks> /// This should be nested inside <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}"/> but is not due to https://github.com/dotnet/roslyn/issues/36992 . /// </remarks> internal enum RegionPlace { Before, Inside, After }; }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// An abstract flow pass that takes some shortcuts in analyzing finally blocks, in order to enable /// the analysis to take place without tracking exceptions or repeating the analysis of a finally block /// for each exit from a try statement. The shortcut results in a slightly less precise /// (but still conservative) analysis, but that less precise analysis is all that is required for /// the language specification. The most significant shortcut is that we do not track the state /// where exceptions can arise. That does not affect the soundness for most analyses, but for those /// analyses whose soundness would be affected (e.g. "data flows out"), we track "unassignments" to keep /// the analysis sound. /// </summary> /// <remarks> /// Formally, this is a fairly conventional lattice flow analysis (<see /// href="https://en.wikipedia.org/wiki/Data-flow_analysis"/>) that moves upward through the <see cref="Join(ref /// TLocalState, ref TLocalState)"/> operation. /// </remarks> internal abstract partial class AbstractFlowPass<TLocalState, TLocalFunctionState> : BoundTreeVisitor where TLocalState : AbstractFlowPass<TLocalState, TLocalFunctionState>.ILocalState where TLocalFunctionState : AbstractFlowPass<TLocalState, TLocalFunctionState>.AbstractLocalFunctionState { protected int _recursionDepth; /// <summary> /// The compilation in which the analysis is taking place. This is needed to determine which /// conditional methods will be compiled and which will be omitted. /// </summary> protected readonly CSharpCompilation compilation; /// <summary> /// The method whose body is being analyzed, or the field whose initializer is being analyzed. /// May be a top-level member or a lambda or local function. It is used for /// references to method parameters. Thus, '_symbol' should not be used directly, but /// 'MethodParameters', 'MethodThisParameter' and 'AnalyzeOutParameters(...)' should be used /// instead. _symbol is null during speculative binding. /// </summary> protected readonly Symbol _symbol; /// <summary> /// Reflects the enclosing member, lambda or local function at the current location (in the bound tree). /// </summary> protected Symbol CurrentSymbol; /// <summary> /// The bound node of the method or initializer being analyzed. /// </summary> protected readonly BoundNode methodMainNode; /// <summary> /// The flow analysis state at each label, computed by calling <see cref="Join(ref /// TLocalState, ref TLocalState)"/> on the state from branches to that label with the state /// when we fall into the label. Entries are created when the label is encountered. One /// case deserves special attention: when the destination of the branch is a label earlier /// in the code, it is possible (though rarely occurs in practice) that we are changing the /// state at a label that we've already analyzed. In that case we run another pass of the /// analysis to allow those changes to propagate. This repeats until no further changes to /// the state of these labels occurs. This can result in quadratic performance in unlikely /// but possible code such as this: "int x; if (cond) goto l1; x = 3; l5: print x; l4: goto /// l5; l3: goto l4; l2: goto l3; l1: goto l2;" /// </summary> private readonly PooledDictionary<LabelSymbol, TLocalState> _labels; /// <summary> /// Set to true after an analysis scan if the analysis was incomplete due to state changing /// after it was used by another analysis component. In this case the caller scans again (until /// this is false). Since the analysis proceeds by monotonically changing the state computed /// at each label, this must terminate. /// </summary> protected bool stateChangedAfterUse; /// <summary> /// All of the labels seen so far in this forward scan of the body /// </summary> private PooledHashSet<BoundStatement> _labelsSeen; /// <summary> /// Pending escapes generated in the current scope (or more deeply nested scopes). When jump /// statements (goto, break, continue, return) are processed, they are placed in the /// pendingBranches buffer to be processed later by the code handling the destination /// statement. As a special case, the processing of try-finally statements might modify the /// contents of the pendingBranches buffer to take into account the behavior of /// "intervening" finally clauses. /// </summary> protected ArrayBuilder<PendingBranch> PendingBranches { get; private set; } /// <summary> /// The definite assignment and/or reachability state at the point currently being analyzed. /// </summary> protected TLocalState State; protected TLocalState StateWhenTrue; protected TLocalState StateWhenFalse; protected bool IsConditionalState; /// <summary> /// Indicates that the transfer function for a particular node (the function mapping the /// state before the node to the state after the node) is not monotonic, in the sense that /// it can change the state in either direction in the lattice. If the transfer function is /// monotonic, the transfer function can only change the state toward the <see /// cref="UnreachableState"/>. Reachability and definite assignment are monotonic, and /// permit a more efficient analysis. Region analysis and nullable analysis are not /// monotonic. This is just an optimization; we could treat all of them as nonmonotonic /// without much loss of performance. In fact, this only affects the analysis of (relatively /// rare) try statements, and is only a slight optimization. /// </summary> private readonly bool _nonMonotonicTransfer; protected void SetConditionalState((TLocalState whenTrue, TLocalState whenFalse) state) { SetConditionalState(state.whenTrue, state.whenFalse); } protected void SetConditionalState(TLocalState whenTrue, TLocalState whenFalse) { IsConditionalState = true; State = default(TLocalState); StateWhenTrue = whenTrue; StateWhenFalse = whenFalse; } protected void SetState(TLocalState newState) { Debug.Assert(newState != null); StateWhenTrue = StateWhenFalse = default(TLocalState); IsConditionalState = false; State = newState; } protected void Split() { if (!IsConditionalState) { SetConditionalState(State, State.Clone()); } } protected void Unsplit() { if (IsConditionalState) { Join(ref StateWhenTrue, ref StateWhenFalse); SetState(StateWhenTrue); } } /// <summary> /// Where all diagnostics are deposited. /// </summary> protected DiagnosticBag Diagnostics { get; } #region Region // For region analysis, we maintain some extra data. protected RegionPlace regionPlace; // tells whether we are currently analyzing code before, during, or after the region protected readonly BoundNode firstInRegion, lastInRegion; protected readonly bool TrackingRegions; /// <summary> /// A cache of the state at the backward branch point of each loop. This is not needed /// during normal flow analysis, but is needed for DataFlowsOut region analysis. /// </summary> private readonly Dictionary<BoundLoopStatement, TLocalState> _loopHeadState; #endregion Region protected AbstractFlowPass( CSharpCompilation compilation, Symbol symbol, BoundNode node, BoundNode firstInRegion = null, BoundNode lastInRegion = null, bool trackRegions = false, bool nonMonotonicTransferFunction = false) { Debug.Assert(node != null); if (firstInRegion != null && lastInRegion != null) { trackRegions = true; } if (trackRegions) { Debug.Assert(firstInRegion != null); Debug.Assert(lastInRegion != null); int startLocation = firstInRegion.Syntax.SpanStart; int endLocation = lastInRegion.Syntax.Span.End; int length = endLocation - startLocation; Debug.Assert(length >= 0, "last comes before first"); this.RegionSpan = new TextSpan(startLocation, length); } PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); _labels = PooledDictionary<LabelSymbol, TLocalState>.GetInstance(); this.Diagnostics = DiagnosticBag.GetInstance(); this.compilation = compilation; _symbol = symbol; CurrentSymbol = symbol; this.methodMainNode = node; this.firstInRegion = firstInRegion; this.lastInRegion = lastInRegion; _loopHeadState = new Dictionary<BoundLoopStatement, TLocalState>(ReferenceEqualityComparer.Instance); TrackingRegions = trackRegions; _nonMonotonicTransfer = nonMonotonicTransferFunction; } protected abstract string Dump(TLocalState state); protected string Dump() { return IsConditionalState ? $"true: {Dump(this.StateWhenTrue)} false: {Dump(this.StateWhenFalse)}" : Dump(this.State); } #if DEBUG protected string DumpLabels() { StringBuilder result = new StringBuilder(); result.Append("Labels{"); bool first = true; foreach (var key in _labels.Keys) { if (!first) { result.Append(", "); } string name = key.Name; if (string.IsNullOrEmpty(name)) { name = "<Label>" + key.GetHashCode(); } result.Append(name).Append(": ").Append(this.Dump(_labels[key])); first = false; } result.Append("}"); return result.ToString(); } #endif private void EnterRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.firstInRegion && this.regionPlace == RegionPlace.Before) { EnterRegion(); } } /// <summary> /// Subclasses may override EnterRegion to perform any actions at the entry to the region. /// </summary> protected virtual void EnterRegion() { Debug.Assert(this.regionPlace == RegionPlace.Before); this.regionPlace = RegionPlace.Inside; } private void LeaveRegionIfNeeded(BoundNode node) { if (TrackingRegions && node == this.lastInRegion && this.regionPlace == RegionPlace.Inside) { LeaveRegion(); } } /// <summary> /// Subclasses may override LeaveRegion to perform any action at the end of the region. /// </summary> protected virtual void LeaveRegion() { Debug.Assert(IsInside); this.regionPlace = RegionPlace.After; } protected readonly TextSpan RegionSpan; protected bool RegionContains(TextSpan span) { // TODO: There are no scenarios involving a zero-length span // currently. If the assert fails, add a corresponding test. Debug.Assert(span.Length > 0); if (span.Length == 0) { return RegionSpan.Contains(span.Start); } return RegionSpan.Contains(span); } protected bool IsInside { get { return regionPlace == RegionPlace.Inside; } } protected virtual void EnterParameters(ImmutableArray<ParameterSymbol> parameters) { foreach (var parameter in parameters) { EnterParameter(parameter); } } protected virtual void EnterParameter(ParameterSymbol parameter) { } protected virtual void LeaveParameters( ImmutableArray<ParameterSymbol> parameters, SyntaxNode syntax, Location location) { foreach (ParameterSymbol parameter in parameters) { LeaveParameter(parameter, syntax, location); } } protected virtual void LeaveParameter(ParameterSymbol parameter, SyntaxNode syntax, Location location) { } public override BoundNode Visit(BoundNode node) { return VisitAlways(node); } protected BoundNode VisitAlways(BoundNode node) { BoundNode result = null; // We scan even expressions, because we must process lambdas contained within them. if (node != null) { EnterRegionIfNeeded(node); VisitWithStackGuard(node); LeaveRegionIfNeeded(node); } return result; } [DebuggerStepThrough] private BoundNode VisitWithStackGuard(BoundNode node) { var expression = node as BoundExpression; if (expression != null) { return VisitExpressionWithStackGuard(ref _recursionDepth, expression); } return base.Visit(node); } [DebuggerStepThrough] protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)base.Visit(node); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; // just let the original exception bubble up. } /// <summary> /// A pending branch. These are created for a return, break, continue, goto statement, /// yield return, yield break, await expression, and await foreach/using. The idea is that /// we don't know if the branch will eventually reach its destination because of an /// intervening finally block that cannot complete normally. So we store them up and handle /// them as we complete processing each construct. At the end of a block, if there are any /// pending branches to a label in that block we process the branch. Otherwise we relay it /// up to the enclosing construct as a pending branch of the enclosing construct. /// </summary> internal class PendingBranch { public readonly BoundNode Branch; public bool IsConditionalState; public TLocalState State; public TLocalState StateWhenTrue; public TLocalState StateWhenFalse; public readonly LabelSymbol Label; public PendingBranch(BoundNode branch, TLocalState state, LabelSymbol label, bool isConditionalState = false, TLocalState stateWhenTrue = default, TLocalState stateWhenFalse = default) { this.Branch = branch; this.State = state.Clone(); this.IsConditionalState = isConditionalState; if (isConditionalState) { this.StateWhenTrue = stateWhenTrue.Clone(); this.StateWhenFalse = stateWhenFalse.Clone(); } this.Label = label; } } /// <summary> /// Perform a single pass of flow analysis. Note that after this pass, /// this.backwardBranchChanged indicates if a further pass is required. /// </summary> protected virtual ImmutableArray<PendingBranch> Scan(ref bool badRegion) { var oldPending = SavePending(); Visit(methodMainNode); this.Unsplit(); RestorePending(oldPending); if (TrackingRegions && regionPlace != RegionPlace.After) { badRegion = true; } ImmutableArray<PendingBranch> result = RemoveReturns(); return result; } protected ImmutableArray<PendingBranch> Analyze(ref bool badRegion, Optional<TLocalState> initialState = default) { ImmutableArray<PendingBranch> returns; do { // the entry point of a method is assumed reachable regionPlace = RegionPlace.Before; this.State = initialState.HasValue ? initialState.Value : TopState(); PendingBranches.Clear(); this.stateChangedAfterUse = false; this.Diagnostics.Clear(); returns = this.Scan(ref badRegion); } while (this.stateChangedAfterUse); return returns; } protected virtual void Free() { this.Diagnostics.Free(); PendingBranches.Free(); _labelsSeen.Free(); _labels.Free(); } /// <summary> /// If a method is currently being analyzed returns its parameters, returns an empty array /// otherwise. /// </summary> protected ImmutableArray<ParameterSymbol> MethodParameters { get { var method = _symbol as MethodSymbol; return (object)method == null ? ImmutableArray<ParameterSymbol>.Empty : method.Parameters; } } /// <summary> /// If a method is currently being analyzed returns its 'this' parameter, returns null /// otherwise. /// </summary> protected ParameterSymbol MethodThisParameter { get { ParameterSymbol thisParameter = null; (_symbol as MethodSymbol)?.TryGetThisParameter(out thisParameter); return thisParameter; } } /// <summary> /// Specifies whether or not method's out parameters should be analyzed. If there's more /// than one location in the method being analyzed, then the method is partial and we prefer /// to report an out parameter in partial method error. /// </summary> /// <param name="location">location to be used</param> /// <returns>true if the out parameters of the method should be analyzed</returns> protected bool ShouldAnalyzeOutParameters(out Location location) { var method = _symbol as MethodSymbol; if ((object)method == null || method.Locations.Length != 1) { location = null; return false; } else { location = method.Locations[0]; return true; } } /// <summary> /// Return the flow analysis state associated with a label. /// </summary> /// <param name="label"></param> /// <returns></returns> protected virtual TLocalState LabelState(LabelSymbol label) { TLocalState result; if (_labels.TryGetValue(label, out result)) { return result; } result = UnreachableState(); _labels.Add(label, result); return result; } /// <summary> /// Return to the caller the set of pending return statements. /// </summary> /// <returns></returns> protected virtual ImmutableArray<PendingBranch> RemoveReturns() { ImmutableArray<PendingBranch> result; result = PendingBranches.ToImmutable(); PendingBranches.Clear(); // The caller should have handled and cleared labelsSeen. Debug.Assert(_labelsSeen.Count == 0); return result; } /// <summary> /// Set the current state to one that indicates that it is unreachable. /// </summary> protected void SetUnreachable() { this.State = UnreachableState(); } protected void VisitLvalue(BoundExpression node) { EnterRegionIfNeeded(node); switch (node?.Kind) { case BoundKind.Parameter: VisitLvalueParameter((BoundParameter)node); break; case BoundKind.Local: VisitLvalue((BoundLocal)node); break; case BoundKind.ThisReference: case BoundKind.BaseReference: break; case BoundKind.PropertyAccess: var access = (BoundPropertyAccess)node; if (Binder.AccessingAutoPropertyFromConstructor(access, _symbol)) { var backingField = (access.PropertySymbol as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(access.ReceiverOpt, backingField); break; } } goto default; case BoundKind.FieldAccess: { BoundFieldAccess node1 = (BoundFieldAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.FieldSymbol); break; } case BoundKind.EventAccess: { BoundEventAccess node1 = (BoundEventAccess)node; VisitFieldAccessInternal(node1.ReceiverOpt, node1.EventSymbol.AssociatedField); break; } case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: ((BoundTupleExpression)node).VisitAllElements((x, self) => self.VisitLvalue(x), this); break; default: VisitRvalue(node); break; } LeaveRegionIfNeeded(node); } protected virtual void VisitLvalue(BoundLocal node) { } /// <summary> /// Visit a boolean condition expression. /// </summary> /// <param name="node"></param> protected void VisitCondition(BoundExpression node) { Visit(node); AdjustConditionalState(node); } private void AdjustConditionalState(BoundExpression node) { if (IsConstantTrue(node)) { Unsplit(); SetConditionalState(this.State, UnreachableState()); } else if (IsConstantFalse(node)) { Unsplit(); SetConditionalState(UnreachableState(), this.State); } else if ((object)node.Type == null || node.Type.SpecialType != SpecialType.System_Boolean) { // a dynamic type or a type with operator true/false Unsplit(); } Split(); } /// <summary> /// Visit a general expression, where we will only need to determine if variables are /// assigned (or not). That is, we will not be needing AssignedWhenTrue and /// AssignedWhenFalse. /// </summary> /// <param name="isKnownToBeAnLvalue">True when visiting an rvalue that will actually be used as an lvalue, /// for example a ref parameter when simulating a read of it, or an argument corresponding to an in parameter</param> protected virtual void VisitRvalue(BoundExpression node, bool isKnownToBeAnLvalue = false) { Visit(node); Unsplit(); } /// <summary> /// Visit a statement. /// </summary> [DebuggerHidden] protected virtual void VisitStatement(BoundStatement statement) { Visit(statement); Debug.Assert(!this.IsConditionalState); } protected static bool IsConstantTrue(BoundExpression node) { return node.ConstantValue == ConstantValue.True; } protected static bool IsConstantFalse(BoundExpression node) { return node.ConstantValue == ConstantValue.False; } protected static bool IsConstantNull(BoundExpression node) { return node.ConstantValue == ConstantValue.Null; } /// <summary> /// Called at the point in a loop where the backwards branch would go to. /// </summary> private void LoopHead(BoundLoopStatement node) { TLocalState previousState; if (_loopHeadState.TryGetValue(node, out previousState)) { Join(ref this.State, ref previousState); } _loopHeadState[node] = this.State.Clone(); } /// <summary> /// Called at the point in a loop where the backward branch is placed. /// </summary> private void LoopTail(BoundLoopStatement node) { var oldState = _loopHeadState[node]; if (Join(ref oldState, ref this.State)) { _loopHeadState[node] = oldState; this.stateChangedAfterUse = true; } } /// <summary> /// Used to resolve break statements in each statement form that has a break statement /// (loops, switch). /// </summary> private void ResolveBreaks(TLocalState breakState, LabelSymbol label) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { Join(ref breakState, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } SetState(breakState); } /// <summary> /// Used to resolve continue statements in each statement form that supports it. /// </summary> private void ResolveContinues(LabelSymbol continueLabel) { var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == continueLabel) { // Technically, nothing in the language specification depends on the state // at the continue label, so we could just discard them instead of merging // the states. In fact, we need not have added continue statements to the // pending jump queue in the first place if we were interested solely in the // flow analysis. However, region analysis (in support of extract method) // and other forms of more precise analysis // depend on continue statements appearing in the pending branch queue, so // we process them from the queue here. Join(ref this.State, ref pending.State); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } } /// <summary> /// Subclasses override this if they want to take special actions on processing a goto /// statement, when both the jump and the label have been located. /// </summary> protected virtual void NoteBranch(PendingBranch pending, BoundNode gotoStmt, BoundStatement target) { target.AssertIsLabeledStatement(); } /// <summary> /// To handle a label, we resolve all branches to that label. Returns true if the state of /// the label changes as a result. /// </summary> /// <param name="label">Target label</param> /// <param name="target">Statement containing the target label</param> private bool ResolveBranches(LabelSymbol label, BoundStatement target) { target?.AssertIsLabeledStatementWithLabel(label); bool labelStateChanged = false; var pendingBranches = PendingBranches; var count = pendingBranches.Count; if (count != 0) { int stillPending = 0; for (int i = 0; i < count; i++) { var pending = pendingBranches[i]; if (pending.Label == label) { ResolveBranch(pending, label, target, ref labelStateChanged); } else { if (stillPending != i) { pendingBranches[stillPending] = pending; } stillPending++; } } pendingBranches.Clip(stillPending); } return labelStateChanged; } protected virtual void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged) { var state = LabelState(label); if (target != null) { NoteBranch(pending, pending.Branch, target); } var changed = Join(ref state, ref pending.State); if (changed) { labelStateChanged = true; _labels[label] = state; } } protected struct SavedPending { public readonly ArrayBuilder<PendingBranch> PendingBranches; public readonly PooledHashSet<BoundStatement> LabelsSeen; public SavedPending(ArrayBuilder<PendingBranch> pendingBranches, PooledHashSet<BoundStatement> labelsSeen) { this.PendingBranches = pendingBranches; this.LabelsSeen = labelsSeen; } } /// <summary> /// Since branches cannot branch into constructs, only out, we save the pending branches /// when visiting more nested constructs. When tracking exceptions, we store the current /// state as the exception state for the following code. /// </summary> protected SavedPending SavePending() { Debug.Assert(!this.IsConditionalState); var result = new SavedPending(PendingBranches, _labelsSeen); PendingBranches = ArrayBuilder<PendingBranch>.GetInstance(); _labelsSeen = PooledHashSet<BoundStatement>.GetInstance(); return result; } /// <summary> /// We use this when closing a block that may contain labels or branches /// - branches to new labels are resolved /// - new labels are removed (no longer can be reached) /// - unresolved pending branches are carried forward /// </summary> /// <param name="oldPending">The old pending branches, which are to be merged with the current ones</param> protected void RestorePending(SavedPending oldPending) { foreach (var node in _labelsSeen) { switch (node.Kind) { case BoundKind.LabeledStatement: { var label = (BoundLabeledStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.LabelStatement: { var label = (BoundLabelStatement)node; stateChangedAfterUse |= ResolveBranches(label.Label, label); } break; case BoundKind.SwitchSection: { var sec = (BoundSwitchSection)node; foreach (var label in sec.SwitchLabels) { stateChangedAfterUse |= ResolveBranches(label.Label, sec); } } break; default: // there are no other kinds of labels throw ExceptionUtilities.UnexpectedValue(node.Kind); } } oldPending.PendingBranches.AddRange(this.PendingBranches); PendingBranches.Free(); PendingBranches = oldPending.PendingBranches; // We only use SavePending/RestorePending when there could be no branch into the region between them. // So there is no need to save the labels seen between the calls. If there were such a need, we would // do "this.labelsSeen.UnionWith(oldPending.LabelsSeen);" instead of the following assignment _labelsSeen.Free(); _labelsSeen = oldPending.LabelsSeen; } #region visitors /// <summary> /// Since each language construct must be handled according to the rules of the language specification, /// the default visitor reports that the construct for the node is not implemented in the compiler. /// </summary> public override BoundNode DefaultVisit(BoundNode node) { Debug.Assert(false, $"Should Visit{node.Kind} be overridden in {this.GetType().Name}?"); Diagnostics.Add(ErrorCode.ERR_InternalError, node.Syntax.Location); return null; } public override BoundNode VisitAttribute(BoundAttribute node) { // No flow analysis is ever done in attributes (or their arguments). return null; } public override BoundNode VisitThrowExpression(BoundThrowExpression node) { VisitRvalue(node.Expression); SetUnreachable(); return node; } public override BoundNode VisitPassByCopy(BoundPassByCopy node) { VisitRvalue(node.Expression); return node; } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); bool negated = node.Pattern.IsNegated(out var pattern); Debug.Assert(negated == node.IsNegated); if (VisitPossibleConditionalAccess(node.Expression, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(patternMatchesNull(pattern) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); } else if (IsConditionalState) { // Patterns which only match a single boolean value should propagate conditional state // for example, `(a != null && a.M(out x)) is true` should have the same conditional state as `(a != null && a.M(out x))`. if (isBoolTest(pattern) is bool value) { if (!value) { SetConditionalState(StateWhenFalse, StateWhenTrue); } } else { // Patterns which match more than a single boolean value cannot propagate conditional state // for example, `(a != null && a.M(out x)) is bool b` should not have conditional state Unsplit(); } } VisitPattern(pattern); var reachableLabels = node.DecisionDag.ReachableLabels; if (!reachableLabels.Contains(node.WhenTrueLabel)) { SetState(this.StateWhenFalse); SetConditionalState(UnreachableState(), this.State); } else if (!reachableLabels.Contains(node.WhenFalseLabel)) { SetState(this.StateWhenTrue); SetConditionalState(this.State, UnreachableState()); } if (negated) { SetConditionalState(this.StateWhenFalse, this.StateWhenTrue); } return node; static bool patternMatchesNull(BoundPattern pattern) { switch (pattern) { case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern { IsVar: false }: case BoundConstantPattern { ConstantValue: { IsNull: false } }: return false; case BoundConstantPattern { ConstantValue: { IsNull: true } }: return true; case BoundNegatedPattern negated: return !patternMatchesNull(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `a?.b(out x) is null or C` // pattern matches null if either subpattern matches null var leftNullTest = patternMatchesNull(binary.Left); return patternMatchesNull(binary.Left) || patternMatchesNull(binary.Right); } // `a?.b out x is not null and var c` // pattern matches null only if both subpatterns match null return patternMatchesNull(binary.Left) && patternMatchesNull(binary.Right); case BoundDeclarationPattern { IsVar: true }: case BoundDiscardPattern: return true; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } // Returns `true` if the pattern only matches a `true` input. // Returns `false` if the pattern only matches a `false` input. // Otherwise, returns `null`. static bool? isBoolTest(BoundPattern pattern) { switch (pattern) { case BoundConstantPattern { ConstantValue: { IsBoolean: true, BooleanValue: var boolValue } }: return boolValue; case BoundNegatedPattern negated: return !isBoolTest(negated.Negated); case BoundBinaryPattern binary: if (binary.Disjunction) { // `(a != null && a.b(out x)) is true or true` matches `true` // `(a != null && a.b(out x)) is true or false` matches any boolean // both subpatterns must have the same bool test for the test to propagate out var leftNullTest = isBoolTest(binary.Left); return leftNullTest is null ? null : leftNullTest != isBoolTest(binary.Right) ? null : leftNullTest; } // `(a != null && a.b(out x)) is true and true` matches `true` // `(a != null && a.b(out x)) is true and var x` matches `true` // `(a != null && a.b(out x)) is true and false` never matches and is a compile error return isBoolTest(binary.Left) ?? isBoolTest(binary.Right); case BoundConstantPattern { ConstantValue: { IsBoolean: false } }: case BoundDiscardPattern: case BoundTypePattern: case BoundRecursivePattern: case BoundITuplePattern: case BoundRelationalPattern: case BoundDeclarationPattern: return null; default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } } public virtual void VisitPattern(BoundPattern pattern) { Split(); } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { // All patterns are handled by VisitPattern throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTupleLiteral(BoundTupleLiteral node) { return VisitTupleExpression(node); } public override BoundNode VisitConvertedTupleLiteral(BoundConvertedTupleLiteral node) { return VisitTupleExpression(node); } private BoundNode VisitTupleExpression(BoundTupleExpression node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), null); return null; } public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node) { VisitRvalue(node.Left); VisitRvalue(node.Right); return null; } public override BoundNode VisitDynamicObjectCreationExpression(BoundDynamicObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitDynamicIndexerAccess(BoundDynamicIndexerAccess node) { VisitRvalue(node.Receiver); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitDynamicMemberAccess(BoundDynamicMemberAccess node) { VisitRvalue(node.Receiver); return null; } public override BoundNode VisitDynamicInvocation(BoundDynamicInvocation node) { VisitRvalue(node.Expression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } #nullable enable protected BoundNode? VisitInterpolatedStringBase(BoundInterpolatedStringBase node, InterpolatedStringHandlerData? data) { // If there can be any branching, then we need to treat the expressions // as optionally evaluated. Otherwise, we treat them as always evaluated (BoundExpression? construction, bool useBoolReturns, bool firstPartIsConditional) = data switch { null => (null, false, false), { } d => (d.Construction, d.UsesBoolReturns, d.HasTrailingHandlerValidityParameter) }; VisitRvalue(construction); bool hasConditionalEvaluation = useBoolReturns || firstPartIsConditional; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; _ = VisitInterpolatedStringHandlerParts(node, useBoolReturns, firstPartIsConditional, ref shortCircuitState); if (hasConditionalEvaluation) { Debug.Assert(shortCircuitState != null); Join(ref this.State, ref shortCircuitState); } return null; } #nullable disable public override BoundNode VisitInterpolatedString(BoundInterpolatedString node) { return VisitInterpolatedStringBase(node, node.InterpolationData); } public override BoundNode VisitUnconvertedInterpolatedString(BoundUnconvertedInterpolatedString node) { // If the node is unconverted, we'll just treat it as if the contents are always evaluated return VisitInterpolatedStringBase(node, data: null); } public override BoundNode VisitStringInsert(BoundStringInsert node) { VisitRvalue(node.Value); if (node.Alignment != null) { VisitRvalue(node.Alignment); } if (node.Format != null) { VisitRvalue(node.Format); } return null; } public override BoundNode VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { return null; } public override BoundNode VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { return null; } public override BoundNode VisitArgList(BoundArgList node) { // The "__arglist" expression that is legal inside a varargs method has no // effect on flow analysis and it has no children. return null; } public override BoundNode VisitArgListOperator(BoundArgListOperator node) { // When we have M(__arglist(x, y, z)) we must visit x, y and z. VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, null); return null; } public override BoundNode VisitRefTypeOperator(BoundRefTypeOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitMakeRefOperator(BoundMakeRefOperator node) { // Note that we require that the variable whose reference we are taking // has been initialized; it is similar to passing the variable as a ref parameter. VisitRvalue(node.Operand, isKnownToBeAnLvalue: true); return null; } public override BoundNode VisitRefValueOperator(BoundRefValueOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitGlobalStatementInitializer(BoundGlobalStatementInitializer node) { VisitStatement(node.Statement); return null; } public override BoundNode VisitLambda(BoundLambda node) => null; public override BoundNode VisitLocal(BoundLocal node) { SplitIfBooleanConstant(node); return null; } public override BoundNode VisitLocalDeclaration(BoundLocalDeclaration node) { if (node.InitializerOpt != null) { // analyze the expression VisitRvalue(node.InitializerOpt, isKnownToBeAnLvalue: node.LocalSymbol.RefKind != RefKind.None); // byref assignment is also a potential write if (node.LocalSymbol.RefKind != RefKind.None) { WriteArgument(node.InitializerOpt, node.LocalSymbol.RefKind, method: null); } } return null; } public override BoundNode VisitBlock(BoundBlock node) { VisitStatements(node.Statements); return null; } private void VisitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { VisitStatement(statement); } } public override BoundNode VisitScope(BoundScope node) { VisitStatements(node.Statements); return null; } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitCall(BoundCall node) { // If the method being called is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // definite assignment analysis. bool callsAreOmitted = node.Method.CallsAreOmitted(node.SyntaxTree); TLocalState savedState = default(TLocalState); if (callsAreOmitted) { savedState = this.State.Clone(); SetUnreachable(); } VisitReceiverBeforeCall(node.ReceiverOpt, node.Method); VisitArgumentsBeforeCall(node.Arguments, node.ArgumentRefKindsOpt); if (node.Method?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: true); } VisitArgumentsAfterCall(node.Arguments, node.ArgumentRefKindsOpt, node.Method); VisitReceiverAfterCall(node.ReceiverOpt, node.Method); if (callsAreOmitted) { this.State = savedState; } return null; } protected void VisitLocalFunctionUse(LocalFunctionSymbol symbol, SyntaxNode syntax, bool isCall) { var localFuncState = GetOrCreateLocalFuncUsages(symbol); VisitLocalFunctionUse(symbol, localFuncState, syntax, isCall); } protected virtual void VisitLocalFunctionUse( LocalFunctionSymbol symbol, TLocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { if (isCall) { Join(ref State, ref localFunctionState.StateFromBottom); Meet(ref State, ref localFunctionState.StateFromTop); } localFunctionState.Visited = true; } private void VisitReceiverBeforeCall(BoundExpression receiverOpt, MethodSymbol method) { if (method is null || method.MethodKind != MethodKind.Constructor) { VisitRvalue(receiverOpt); } } private void VisitReceiverAfterCall(BoundExpression receiverOpt, MethodSymbol method) { if (receiverOpt is null) { return; } if (method is null) { WriteArgument(receiverOpt, RefKind.Ref, method: null); } else if (method.TryGetThisParameter(out var thisParameter) && thisParameter is object && !TypeIsImmutable(thisParameter.Type)) { var thisRefKind = thisParameter.RefKind; if (thisRefKind.IsWritableReference()) { WriteArgument(receiverOpt, thisRefKind, method); } } } /// <summary> /// Certain (struct) types are known by the compiler to be immutable. In these cases calling a method on /// the type is known (by flow analysis) not to write the receiver. /// </summary> /// <param name="t"></param> /// <returns></returns> private static bool TypeIsImmutable(TypeSymbol t) { switch (t.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_DateTime: return true; default: return t.IsNullableType(); } } public override BoundNode VisitIndexerAccess(BoundIndexerAccess node) { var method = GetReadMethod(node.Indexer); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); if ((object)method != null) { VisitReceiverAfterCall(node.ReceiverOpt, method); } return null; } public override BoundNode VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { // Index or Range pattern indexers evaluate the following in order: // 1. The receiver // 1. The Count or Length method off the receiver // 2. The argument to the access // 3. The pattern method VisitRvalue(node.Receiver); var method = GetReadMethod(node.LengthOrCountProperty); VisitReceiverAfterCall(node.Receiver, method); VisitRvalue(node.Argument); method = node.PatternSymbol switch { PropertySymbol p => GetReadMethod(p), MethodSymbol m => m, _ => throw ExceptionUtilities.UnexpectedValue(node.PatternSymbol) }; VisitReceiverAfterCall(node.Receiver, method); return null; } public override BoundNode VisitEventAssignmentOperator(BoundEventAssignmentOperator node) { VisitRvalue(node.ReceiverOpt); VisitRvalue(node.Argument); return null; } /// <summary> /// Do not call for a local function. /// </summary> protected virtual void VisitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { Debug.Assert(method?.OriginalDefinition.MethodKind != MethodKind.LocalFunction); VisitArgumentsBeforeCall(arguments, refKindsOpt); VisitArgumentsAfterCall(arguments, refKindsOpt, method); } private void VisitArgumentsBeforeCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt) { // first value and ref parameters are read... for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); if (refKind != RefKind.Out) { VisitRvalue(arguments[i], isKnownToBeAnLvalue: refKind != RefKind.None); } else { VisitLvalue(arguments[i]); } } } /// <summary> /// Writes ref and out parameters /// </summary> private void VisitArgumentsAfterCall(ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, MethodSymbol method) { for (int i = 0; i < arguments.Length; i++) { RefKind refKind = GetRefKind(refKindsOpt, i); // passing as a byref argument is also a potential write if (refKind != RefKind.None) { WriteArgument(arguments[i], refKind, method); } } } protected static RefKind GetRefKind(ImmutableArray<RefKind> refKindsOpt, int index) { return refKindsOpt.IsDefault || refKindsOpt.Length <= index ? RefKind.None : refKindsOpt[index]; } protected virtual void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method) { } public override BoundNode VisitBadExpression(BoundBadExpression node) { foreach (var child in node.ChildBoundNodes) { VisitRvalue(child as BoundExpression); } return null; } public override BoundNode VisitBadStatement(BoundBadStatement node) { foreach (var child in node.ChildBoundNodes) { if (child is BoundStatement) { VisitStatement(child as BoundStatement); } else { VisitRvalue(child as BoundExpression); } } return null; } // Can be called as part of a bad expression. public override BoundNode VisitArrayInitialization(BoundArrayInitialization node) { foreach (var child in node.Initializers) { VisitRvalue(child); } return null; } public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node) { var methodGroup = node.Argument as BoundMethodGroup; if (methodGroup != null) { if ((object)node.MethodOpt != null && node.MethodOpt.RequiresInstanceReceiver) { EnterRegionIfNeeded(methodGroup); VisitRvalue(methodGroup.ReceiverOpt); LeaveRegionIfNeeded(methodGroup); } else if (node.MethodOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { VisitRvalue(node.Argument); } return null; } public override BoundNode VisitTypeExpression(BoundTypeExpression node) { return null; } public override BoundNode VisitTypeOrValueExpression(BoundTypeOrValueExpression node) { // If we're seeing a node of this kind, then we failed to resolve the member access // as either a type or a property/field/event/local/parameter. In such cases, // the second interpretation applies so just visit the node for that. return this.Visit(node.Data.ValueExpression); } public override BoundNode VisitLiteral(BoundLiteral node) { SplitIfBooleanConstant(node); return null; } protected void SplitIfBooleanConstant(BoundExpression node) { if (node.ConstantValue is { IsBoolean: true, BooleanValue: bool booleanValue }) { var unreachable = UnreachableState(); Split(); if (booleanValue) { StateWhenFalse = unreachable; } else { StateWhenTrue = unreachable; } } } public override BoundNode VisitMethodDefIndex(BoundMethodDefIndex node) { return null; } public override BoundNode VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) { return null; } public override BoundNode VisitModuleVersionId(BoundModuleVersionId node) { return null; } public override BoundNode VisitModuleVersionIdString(BoundModuleVersionIdString node) { return null; } public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) { return null; } public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node) { return null; } public override BoundNode VisitConversion(BoundConversion node) { if (node.ConversionKind == ConversionKind.MethodGroup) { if (node.IsExtensionMethod || ((object)node.SymbolOpt != null && node.SymbolOpt.RequiresInstanceReceiver)) { BoundExpression receiver = ((BoundMethodGroup)node.Operand).ReceiverOpt; // A method group's "implicit this" is only used for instance methods. EnterRegionIfNeeded(node.Operand); VisitRvalue(receiver); LeaveRegionIfNeeded(node.Operand); } else if (node.SymbolOpt?.OriginalDefinition is LocalFunctionSymbol localFunc) { VisitLocalFunctionUse(localFunc, node.Syntax, isCall: false); } } else { Visit(node.Operand); } return null; } public override BoundNode VisitIfStatement(BoundIfStatement node) { // 5.3.3.5 If statements VisitCondition(node.Condition); TLocalState trueState = StateWhenTrue; TLocalState falseState = StateWhenFalse; SetState(trueState); VisitStatement(node.Consequence); trueState = this.State; SetState(falseState); if (node.AlternativeOpt != null) { VisitStatement(node.AlternativeOpt); } Join(ref this.State, ref trueState); return null; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var oldPending = SavePending(); // we do not allow branches into a try statement var initialState = this.State.Clone(); // use this state to resolve all the branches introduced and internal to try/catch var pendingBeforeTry = SavePending(); VisitTryBlockWithAnyTransferFunction(node.TryBlock, node, ref initialState); var finallyState = initialState.Clone(); var endState = this.State; foreach (var catchBlock in node.CatchBlocks) { SetState(initialState.Clone()); VisitCatchBlockWithAnyTransferFunction(catchBlock, ref finallyState); Join(ref endState, ref this.State); } // Give a chance to branches internal to try/catch to resolve. // Carry forward unresolved branches. RestorePending(pendingBeforeTry); // NOTE: At this point all branches that are internal to try or catch blocks have been resolved. // However we have not yet restored the oldPending branches. Therefore all the branches // that are currently pending must have been introduced in try/catch and do not terminate inside those blocks. // // With exception of YieldReturn, these branches logically go through finally, if such present, // so we must Union/Intersect finally state as appropriate if (node.FinallyBlockOpt != null) { // branches from the finally block, while illegal, should still not be considered // to execute the finally block before occurring. Also, we do not handle branches // *into* the finally block. SetState(finallyState); // capture tryAndCatchPending before going into finally // we will need pending branches as they were before finally later var tryAndCatchPending = SavePending(); var stateMovedUpInFinally = ReachableBottomState(); VisitFinallyBlockWithAnyTransferFunction(node.FinallyBlockOpt, ref stateMovedUpInFinally); foreach (var pend in tryAndCatchPending.PendingBranches) { if (pend.Branch == null) { continue; // a tracked exception } if (pend.Branch.Kind != BoundKind.YieldReturnStatement) { updatePendingBranchState(ref pend.State, ref stateMovedUpInFinally); if (pend.IsConditionalState) { updatePendingBranchState(ref pend.StateWhenTrue, ref stateMovedUpInFinally); updatePendingBranchState(ref pend.StateWhenFalse, ref stateMovedUpInFinally); } } } RestorePending(tryAndCatchPending); Meet(ref endState, ref this.State); if (_nonMonotonicTransfer) { Join(ref endState, ref stateMovedUpInFinally); } } SetState(endState); RestorePending(oldPending); return null; void updatePendingBranchState(ref TLocalState stateToUpdate, ref TLocalState stateMovedUpInFinally) { Meet(ref stateToUpdate, ref this.State); if (_nonMonotonicTransfer) { Join(ref stateToUpdate, ref stateMovedUpInFinally); } } } protected Optional<TLocalState> NonMonotonicState; /// <summary> /// Join state from other try block, potentially in a nested method. /// </summary> protected virtual void JoinTryBlockState(ref TLocalState self, ref TLocalState other) { Join(ref self, ref other); } private void VisitTryBlockWithAnyTransferFunction(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitTryBlock(tryBlock, node, ref tryState); var tempTryStateValue = NonMonotonicState.Value; Join(ref tryState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitTryBlock(tryBlock, node, ref tryState); } } protected virtual void VisitTryBlock(BoundStatement tryBlock, BoundTryStatement node, ref TLocalState tryState) { VisitStatement(tryBlock); } private void VisitCatchBlockWithAnyTransferFunction(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitCatchBlock(catchBlock, ref finallyState); var tempTryStateValue = NonMonotonicState.Value; Join(ref finallyState, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitCatchBlock(catchBlock, ref finallyState); } } protected virtual void VisitCatchBlock(BoundCatchBlock catchBlock, ref TLocalState finallyState) { if (catchBlock.ExceptionSourceOpt != null) { VisitLvalue(catchBlock.ExceptionSourceOpt); } if (catchBlock.ExceptionFilterPrologueOpt is { }) { VisitStatementList(catchBlock.ExceptionFilterPrologueOpt); } if (catchBlock.ExceptionFilterOpt != null) { VisitCondition(catchBlock.ExceptionFilterOpt); SetState(StateWhenTrue); } VisitStatement(catchBlock.Body); } private void VisitFinallyBlockWithAnyTransferFunction(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { if (_nonMonotonicTransfer) { Optional<TLocalState> oldTryState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitFinallyBlock(finallyBlock, ref stateMovedUp); var tempTryStateValue = NonMonotonicState.Value; Join(ref stateMovedUp, ref tempTryStateValue); if (oldTryState.HasValue) { var oldTryStateValue = oldTryState.Value; JoinTryBlockState(ref oldTryStateValue, ref tempTryStateValue); oldTryState = oldTryStateValue; } NonMonotonicState = oldTryState; } else { VisitFinallyBlock(finallyBlock, ref stateMovedUp); } } protected virtual void VisitFinallyBlock(BoundStatement finallyBlock, ref TLocalState stateMovedUp) { VisitStatement(finallyBlock); // this should generate no pending branches } public override BoundNode VisitExtractedFinallyBlock(BoundExtractedFinallyBlock node) { return VisitBlock(node.FinallyBlock); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { var result = VisitReturnStatementNoAdjust(node); PendingBranches.Add(new PendingBranch(node, this.State, label: null)); SetUnreachable(); return result; } protected virtual BoundNode VisitReturnStatementNoAdjust(BoundReturnStatement node) { VisitRvalue(node.ExpressionOpt, isKnownToBeAnLvalue: node.RefKind != RefKind.None); // byref return is also a potential write if (node.RefKind != RefKind.None) { WriteArgument(node.ExpressionOpt, node.RefKind, method: null); } return null; } public override BoundNode VisitThisReference(BoundThisReference node) { return null; } public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { return null; } public override BoundNode VisitHostObjectMemberReference(BoundHostObjectMemberReference node) { return null; } public override BoundNode VisitParameter(BoundParameter node) { return null; } protected virtual void VisitLvalueParameter(BoundParameter node) { } public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpression node) { VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.Constructor); VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNewT(BoundNewT node) { VisitRvalue(node.InitializerExpressionOpt); return null; } public override BoundNode VisitNoPiaObjectCreationExpression(BoundNoPiaObjectCreationExpression node) { VisitRvalue(node.InitializerExpressionOpt); return null; } // represents anything that occurs at the invocation of the property setter protected virtual void PropertySetter(BoundExpression node, BoundExpression receiver, MethodSymbol setter, BoundExpression value = null) { VisitReceiverAfterCall(receiver, setter); } // returns false if expression is not a property access // or if the property has a backing field // and accessed in a corresponding constructor private bool RegularPropertyAccess(BoundExpression expr) { if (expr.Kind != BoundKind.PropertyAccess) { return false; } return !Binder.AccessingAutoPropertyFromConstructor((BoundPropertyAccess)expr, _symbol); } public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var method = GetWriteMethod(property); VisitReceiverBeforeCall(left.ReceiverOpt, method); VisitRvalue(node.Right); PropertySetter(node, left.ReceiverOpt, method, node.Right); return null; } } VisitLvalue(node.Left); VisitRvalue(node.Right, isKnownToBeAnLvalue: node.IsRef); // byref assignment is also a potential write if (node.IsRef) { // Assume that BadExpression is a ref location to avoid // cascading diagnostics var refKind = node.Left.Kind == BoundKind.BadExpression ? RefKind.Ref : node.Left.GetRefKind(); WriteArgument(node.Right, refKind, method: null); } return null; } public override BoundNode VisitDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator node) { VisitLvalue(node.Left); VisitRvalue(node.Right); return null; } public sealed override BoundNode VisitOutDeconstructVarPendingInference(OutDeconstructVarPendingInference node) { // OutDeconstructVarPendingInference nodes are only used within initial binding, but don't survive past that stage throw ExceptionUtilities.Unreachable; } public override BoundNode VisitCompoundAssignmentOperator(BoundCompoundAssignmentOperator node) { VisitCompoundAssignmentTarget(node); VisitRvalue(node.Right); AfterRightHasBeenVisited(node); return null; } protected void VisitCompoundAssignmentTarget(BoundCompoundAssignmentOperator node) { // TODO: should events be handled specially too? if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)GetWriteMethod(property)); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); return; } } VisitRvalue(node.Left, isKnownToBeAnLvalue: true); } protected void AfterRightHasBeenVisited(BoundCompoundAssignmentOperator node) { if (RegularPropertyAccess(node.Left)) { var left = (BoundPropertyAccess)node.Left; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var writeMethod = GetWriteMethod(property); PropertySetter(node, left.ReceiverOpt, writeMethod); VisitReceiverAfterCall(left.ReceiverOpt, writeMethod); return; } } } public override BoundNode VisitFieldAccess(BoundFieldAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.FieldSymbol); SplitIfBooleanConstant(node); return null; } private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { bool asLvalue = (object)fieldSymbol != null && (fieldSymbol.IsFixedSizeBuffer || !fieldSymbol.IsStatic && fieldSymbol.ContainingType.TypeKind == TypeKind.Struct && receiverOpt != null && receiverOpt.Kind != BoundKind.TypeExpression && (object)receiverOpt.Type != null && !receiverOpt.Type.IsPrimitiveRecursiveStruct()); if (asLvalue) { VisitLvalue(receiverOpt); } else { VisitRvalue(receiverOpt); } } public override BoundNode VisitFieldInfo(BoundFieldInfo node) { return null; } public override BoundNode VisitMethodInfo(BoundMethodInfo node) { return null; } public override BoundNode VisitPropertyAccess(BoundPropertyAccess node) { var property = node.PropertySymbol; if (Binder.AccessingAutoPropertyFromConstructor(node, _symbol)) { var backingField = (property as SourcePropertySymbolBase)?.BackingField; if (backingField != null) { VisitFieldAccessInternal(node.ReceiverOpt, backingField); return null; } } var method = GetReadMethod(property); VisitReceiverBeforeCall(node.ReceiverOpt, method); VisitReceiverAfterCall(node.ReceiverOpt, method); return null; // TODO: In an expression such as // M().Prop = G(); // Exceptions thrown from M() occur before those from G(), but exceptions from the property accessor // occur after both. The precise abstract flow pass does not yet currently have this quite right. // Probably what is needed is a VisitPropertyAccessInternal(BoundPropertyAccess node, bool read) // which should assume that the receiver will have been handled by the caller. This can be invoked // twice for read/write operations such as // M().Prop += 1 // or at the appropriate place in the sequence for read or write operations. // Do events require any special handling too? } public override BoundNode VisitEventAccess(BoundEventAccess node) { VisitFieldAccessInternal(node.ReceiverOpt, node.EventSymbol.AssociatedField); return null; } public override BoundNode VisitRangeVariable(BoundRangeVariable node) { return null; } public override BoundNode VisitQueryClause(BoundQueryClause node) { VisitRvalue(node.UnoptimizedForm ?? node.Value); return null; } private BoundNode VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { foreach (var v in node.LocalDeclarations) { Visit(v); } return null; } public override BoundNode VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode VisitWhileStatement(BoundWhileStatement node) { // while (node.Condition) { node.Body; node.ContinueLabel: } node.BreakLabel: LoopHead(node); VisitCondition(node.Condition); TLocalState bodyState = StateWhenTrue; TLocalState breakState = StateWhenFalse; SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitWithExpression(BoundWithExpression node) { VisitRvalue(node.Receiver); VisitObjectOrCollectionInitializerExpression(node.InitializerExpression.Initializers); return null; } public override BoundNode VisitArrayAccess(BoundArrayAccess node) { VisitRvalue(node.Expression); foreach (var i in node.Indices) { VisitRvalue(i); } return null; } public override BoundNode VisitBinaryOperator(BoundBinaryOperator node) { if (node.OperatorKind.IsLogical()) { Debug.Assert(!node.OperatorKind.IsUserDefined()); VisitBinaryLogicalOperatorChildren(node); } else if (node.InterpolatedStringHandlerData is { } data) { VisitBinaryInterpolatedStringAddition(node); } else { VisitBinaryOperatorChildren(node); } return null; } public override BoundNode VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { VisitBinaryLogicalOperatorChildren(node); return null; } private void VisitBinaryLogicalOperatorChildren(BoundExpression node) { // Do not blow the stack due to a deep recursion on the left. var stack = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression binary; BoundExpression child = node; while (true) { var childKind = child.Kind; if (childKind == BoundKind.BinaryOperator) { var binOp = (BoundBinaryOperator)child; if (!binOp.OperatorKind.IsLogical()) { break; } Debug.Assert(!binOp.OperatorKind.IsUserDefined()); binary = child; child = binOp.Left; } else if (childKind == BoundKind.UserDefinedConditionalLogicalOperator) { binary = child; child = ((BoundUserDefinedConditionalLogicalOperator)binary).Left; } else { break; } stack.Push(binary); } Debug.Assert(stack.Count > 0); VisitCondition(child); while (true) { binary = stack.Pop(); BinaryOperatorKind kind; BoundExpression right; switch (binary.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)binary; kind = binOp.OperatorKind; right = binOp.Right; break; case BoundKind.UserDefinedConditionalLogicalOperator: var udBinOp = (BoundUserDefinedConditionalLogicalOperator)binary; kind = udBinOp.OperatorKind; right = udBinOp.Right; break; default: throw ExceptionUtilities.UnexpectedValue(binary.Kind); } var op = kind.Operator(); var isAnd = op == BinaryOperatorKind.And; var isBool = kind.OperandTypes() == BinaryOperatorKind.Bool; Debug.Assert(isAnd || op == BinaryOperatorKind.Or); var leftTrue = this.StateWhenTrue; var leftFalse = this.StateWhenFalse; SetState(isAnd ? leftTrue : leftFalse); AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); if (stack.Count == 0) { break; } AdjustConditionalState(binary); } Debug.Assert((object)binary == node); stack.Free(); } protected virtual void AfterLeftChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { Visit(right); // First part of VisitCondition AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(binary, right, isAnd, isBool, ref leftTrue, ref leftFalse); } protected void AfterRightChildOfBinaryLogicalOperatorHasBeenVisited(BoundExpression binary, BoundExpression right, bool isAnd, bool isBool, ref TLocalState leftTrue, ref TLocalState leftFalse) { AdjustConditionalState(right); // Second part of VisitCondition if (!isBool) { this.Unsplit(); this.Split(); } var resultTrue = this.StateWhenTrue; var resultFalse = this.StateWhenFalse; if (isAnd) { Join(ref resultFalse, ref leftFalse); } else { Join(ref resultTrue, ref leftTrue); } SetConditionalState(resultTrue, resultFalse); if (!isBool) { this.Unsplit(); } } private void VisitBinaryOperatorChildren(BoundBinaryOperator node) { // It is common in machine-generated code for there to be deep recursion on the left side of a binary // operator, for example, if you have "a + b + c + ... " then the bound tree will be deep on the left // hand side. To mitigate the risk of stack overflow we use an explicit stack. // // Of course we must ensure that we visit the left hand side before the right hand side. var stack = ArrayBuilder<BoundBinaryOperator>.GetInstance(); BoundBinaryOperator binary = node; do { stack.Push(binary); binary = binary.Left as BoundBinaryOperator; } while (binary != null && !binary.OperatorKind.IsLogical() && binary.InterpolatedStringHandlerData is null); VisitBinaryOperatorChildren(stack); stack.Free(); } #nullable enable protected virtual void VisitBinaryOperatorChildren(ArrayBuilder<BoundBinaryOperator> stack) { var binary = stack.Pop(); // Only the leftmost operator of a left-associative binary operator chain can learn from a conditional access on the left // For simplicity, we just special case it here. // For example, `a?.b(out x) == true` has a conditional access on the left of the operator, // but `expr == a?.b(out x) == true` has a conditional access on the right of the operator if (VisitPossibleConditionalAccess(binary.Left, out var stateWhenNotNull) && canLearnFromOperator(binary) && isKnownNullOrNotNull(binary.Right)) { if (_nonMonotonicTransfer) { // In this very specific scenario, we need to do extra work to track unassignments for region analysis. // See `AbstractFlowPass.VisitCatchBlockWithAnyTransferFunction` for a similar scenario in catch blocks. Optional<TLocalState> oldState = NonMonotonicState; NonMonotonicState = ReachableBottomState(); VisitRvalue(binary.Right); var tempStateValue = NonMonotonicState.Value; Join(ref stateWhenNotNull, ref tempStateValue); if (oldState.HasValue) { var oldStateValue = oldState.Value; Join(ref oldStateValue, ref tempStateValue); oldState = oldStateValue; } NonMonotonicState = oldState; } else { VisitRvalue(binary.Right); Meet(ref stateWhenNotNull, ref State); } var isNullConstant = binary.Right.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); if (stack.Count == 0) { return; } binary = stack.Pop(); } while (true) { if (!canLearnFromOperator(binary) || !learnFromOperator(binary)) { Unsplit(); VisitRvalue(binary.Right); } if (stack.Count == 0) { break; } binary = stack.Pop(); } static bool canLearnFromOperator(BoundBinaryOperator binary) { var kind = binary.OperatorKind; return kind.Operator() is BinaryOperatorKind.Equal or BinaryOperatorKind.NotEqual && (!kind.IsUserDefined() || kind.IsLifted()); } static bool isKnownNullOrNotNull(BoundExpression expr) { return expr.ConstantValue is object || (expr is BoundConversion { ConversionKind: ConversionKind.ExplicitNullable or ConversionKind.ImplicitNullable } conv && conv.Operand.Type!.IsNonNullableValueType()); } static bool isEquals(BoundBinaryOperator binary) => binary.OperatorKind.Operator() == BinaryOperatorKind.Equal; // Returns true if `binary.Right` was visited by the call. bool learnFromOperator(BoundBinaryOperator binary) { // `true == a?.b(out x)` if (isKnownNullOrNotNull(binary.Left) && TryVisitConditionalAccess(binary.Right, out var stateWhenNotNull)) { var isNullConstant = binary.Left.ConstantValue?.IsNull == true; SetConditionalState(isNullConstant == isEquals(binary) ? (State, stateWhenNotNull) : (stateWhenNotNull, State)); return true; } // `a && b(out x) == true` else if (IsConditionalState && binary.Right.ConstantValue is { IsBoolean: true } rightConstant) { var (stateWhenTrue, stateWhenFalse) = (StateWhenTrue.Clone(), StateWhenFalse.Clone()); Unsplit(); Visit(binary.Right); SetConditionalState(isEquals(binary) == rightConstant.BooleanValue ? (stateWhenTrue, stateWhenFalse) : (stateWhenFalse, stateWhenTrue)); return true; } // `true == a && b(out x)` else if (binary.Left.ConstantValue is { IsBoolean: true } leftConstant) { Unsplit(); Visit(binary.Right); if (IsConditionalState && isEquals(binary) != leftConstant.BooleanValue) { SetConditionalState(StateWhenFalse, StateWhenTrue); } return true; } return false; } } protected void VisitBinaryInterpolatedStringAddition(BoundBinaryOperator node) { Debug.Assert(node.InterpolatedStringHandlerData.HasValue); var stack = ArrayBuilder<BoundInterpolatedString>.GetInstance(); var data = node.InterpolatedStringHandlerData.GetValueOrDefault(); while (PushBinaryOperatorInterpolatedStringChildren(node, stack) is { } next) { node = next; } Debug.Assert(stack.Count >= 2); VisitRvalue(data.Construction); bool visitedFirst = false; bool hasTrailingHandlerValidityParameter = data.HasTrailingHandlerValidityParameter; bool hasConditionalEvaluation = data.UsesBoolReturns || hasTrailingHandlerValidityParameter; TLocalState? shortCircuitState = hasConditionalEvaluation ? State.Clone() : default; while (stack.TryPop(out var currentString)) { visitedFirst |= VisitInterpolatedStringHandlerParts(currentString, data.UsesBoolReturns, firstPartIsConditional: visitedFirst || hasTrailingHandlerValidityParameter, ref shortCircuitState); } if (hasConditionalEvaluation) { Join(ref State, ref shortCircuitState); } stack.Free(); } protected virtual BoundBinaryOperator? PushBinaryOperatorInterpolatedStringChildren(BoundBinaryOperator node, ArrayBuilder<BoundInterpolatedString> stack) { stack.Push((BoundInterpolatedString)node.Right); switch (node.Left) { case BoundBinaryOperator next: return next; case BoundInterpolatedString @string: stack.Push(@string); return null; default: throw ExceptionUtilities.UnexpectedValue(node.Left.Kind); } } protected virtual bool VisitInterpolatedStringHandlerParts(BoundInterpolatedStringBase node, bool usesBoolReturns, bool firstPartIsConditional, ref TLocalState? shortCircuitState) { Debug.Assert(shortCircuitState != null || (!usesBoolReturns && !firstPartIsConditional)); if (node.Parts.IsEmpty) { return false; } ReadOnlySpan<BoundExpression> parts; if (firstPartIsConditional) { parts = node.Parts.AsSpan(); } else { VisitRvalue(node.Parts[0]); shortCircuitState = State.Clone(); parts = node.Parts.AsSpan()[1..]; } foreach (var part in parts) { VisitRvalue(part); if (usesBoolReturns) { Debug.Assert(shortCircuitState != null); Join(ref shortCircuitState, ref State); } } return true; } #nullable disable public override BoundNode VisitUnaryOperator(BoundUnaryOperator node) { if (node.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { // We have a special case for the ! unary operator, which can operate in a boolean context (5.3.3.26) VisitCondition(node.Operand); // it inverts the sense of assignedWhenTrue and assignedWhenFalse. SetConditionalState(StateWhenFalse, StateWhenTrue); } else { VisitRvalue(node.Operand); } return null; } public override BoundNode VisitRangeExpression(BoundRangeExpression node) { if (node.LeftOperandOpt != null) { VisitRvalue(node.LeftOperandOpt); } if (node.RightOperandOpt != null) { VisitRvalue(node.RightOperandOpt); } return null; } public override BoundNode VisitFromEndIndexExpression(BoundFromEndIndexExpression node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitIncrementOperator(BoundIncrementOperator node) { // TODO: should we also specially handle events? if (RegularPropertyAccess(node.Operand)) { var left = (BoundPropertyAccess)node.Operand; var property = left.PropertySymbol; if (property.RefKind == RefKind.None) { var readMethod = GetReadMethod(property); var writeMethod = GetWriteMethod(property); Debug.Assert(node.HasAnyErrors || (object)readMethod != (object)writeMethod); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); PropertySetter(node, left.ReceiverOpt, writeMethod); // followed by a write return null; } } VisitRvalue(node.Operand); return null; } public override BoundNode VisitArrayCreation(BoundArrayCreation node) { foreach (var expr in node.Bounds) { VisitRvalue(expr); } if (node.InitializerOpt != null) { VisitArrayInitializationInternal(node, node.InitializerOpt); } return null; } private void VisitArrayInitializationInternal(BoundArrayCreation arrayCreation, BoundArrayInitialization node) { foreach (var child in node.Initializers) { if (child.Kind == BoundKind.ArrayInitialization) { VisitArrayInitializationInternal(arrayCreation, (BoundArrayInitialization)child); } else { VisitRvalue(child); } } } public override BoundNode VisitForStatement(BoundForStatement node) { if (node.Initializer != null) { VisitStatement(node.Initializer); } LoopHead(node); TLocalState bodyState, breakState; if (node.Condition != null) { VisitCondition(node.Condition); bodyState = this.StateWhenTrue; breakState = this.StateWhenFalse; } else { bodyState = this.State; breakState = UnreachableState(); } SetState(bodyState); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); if (node.Increment != null) { VisitStatement(node.Increment); } LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitForEachStatement(BoundForEachStatement node) { // foreach [await] ( var v in node.Expression ) { node.Body; node.ContinueLabel: } node.BreakLabel: VisitForEachExpression(node); var breakState = this.State.Clone(); LoopHead(node); VisitForEachIterationVariables(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); if (AwaitUsingAndForeachAddsPendingBranch && ((CommonForEachStatementSyntax)node.Syntax).AwaitKeyword != default) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } protected virtual void VisitForEachExpression(BoundForEachStatement node) { VisitRvalue(node.Expression); } public virtual void VisitForEachIterationVariables(BoundForEachStatement node) { } public override BoundNode VisitAsOperator(BoundAsOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitIsOperator(BoundIsOperator node) { if (VisitPossibleConditionalAccess(node.Operand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); SetConditionalState(stateWhenNotNull, State); } else { // `(a && b.M(out x)) is bool` should discard conditional state from LHS Unsplit(); } return null; } public override BoundNode VisitMethodGroup(BoundMethodGroup node) { if (node.ReceiverOpt != null) { // An explicit or implicit receiver, for example in an expression such as (x.Goo is Action, or Goo is Action), is considered to be read. VisitRvalue(node.ReceiverOpt); } return null; } #nullable enable public override BoundNode? VisitNullCoalescingOperator(BoundNullCoalescingOperator node) { if (IsConstantNull(node.LeftOperand)) { VisitRvalue(node.LeftOperand); Visit(node.RightOperand); } else { TLocalState savedState; if (VisitPossibleConditionalAccess(node.LeftOperand, out var stateWhenNotNull)) { Debug.Assert(!IsConditionalState); savedState = stateWhenNotNull; } else { Unsplit(); savedState = State.Clone(); } if (node.LeftOperand.ConstantValue != null) { SetUnreachable(); } Visit(node.RightOperand); if (IsConditionalState) { Join(ref StateWhenTrue, ref savedState); Join(ref StateWhenFalse, ref savedState); } else { Join(ref this.State, ref savedState); } } return null; } /// <summary> /// Visits a node only if it is a conditional access. /// Returns 'true' if and only if the node was visited. /// </summary> private bool TryVisitConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { var access = node switch { BoundConditionalAccess ca => ca, BoundConversion { Conversion: Conversion conversion, Operand: BoundConditionalAccess ca } when CanPropagateStateWhenNotNull(conversion) => ca, _ => null }; if (access is not null) { EnterRegionIfNeeded(access); Unsplit(); VisitConditionalAccess(access, out stateWhenNotNull); Debug.Assert(!IsConditionalState); LeaveRegionIfNeeded(access); return true; } stateWhenNotNull = default; return false; } /// <summary> /// "State when not null" can only propagate out of a conditional access if /// it is not subject to a user-defined conversion whose parameter is not of a non-nullable value type. /// </summary> protected static bool CanPropagateStateWhenNotNull(Conversion conversion) { if (!conversion.IsValid) { return false; } if (!conversion.IsUserDefined) { return true; } var method = conversion.Method; Debug.Assert(method is object); Debug.Assert(method.ParameterCount is 1); var param = method.Parameters[0]; return param.Type.IsNonNullableValueType(); } /// <summary> /// Unconditionally visits an expression. /// If the expression has "state when not null" after visiting, /// the method returns 'true' and writes the state to <paramref name="stateWhenNotNull" />. /// </summary> private bool VisitPossibleConditionalAccess(BoundExpression node, [NotNullWhen(true)] out TLocalState? stateWhenNotNull) { if (TryVisitConditionalAccess(node, out stateWhenNotNull)) { return true; } else { Visit(node); return false; } } private void VisitConditionalAccess(BoundConditionalAccess node, out TLocalState stateWhenNotNull) { // The receiver may also be a conditional access. // `(a?.b(x = 1))?.c(y = 1)` if (VisitPossibleConditionalAccess(node.Receiver, out var receiverStateWhenNotNull)) { stateWhenNotNull = receiverStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } if (node.Receiver.ConstantValue != null && !IsConstantNull(node.Receiver)) { // Consider a scenario like `"a"?.M0(x = 1)?.M0(y = 1)`. // We can "know" that `.M0(x = 1)` was evaluated unconditionally but not `M0(y = 1)`. // Therefore we do a VisitPossibleConditionalAccess here which unconditionally includes the "after receiver" state in State // and includes the "after subsequent conditional accesses" in stateWhenNotNull if (VisitPossibleConditionalAccess(node.AccessExpression, out var firstAccessStateWhenNotNull)) { stateWhenNotNull = firstAccessStateWhenNotNull; } else { Unsplit(); stateWhenNotNull = this.State.Clone(); } } else { var savedState = this.State.Clone(); if (IsConstantNull(node.Receiver)) { SetUnreachable(); } else { SetState(stateWhenNotNull); } // We want to preserve stateWhenNotNull from accesses in the same "chain": // a?.b(out x)?.c(out y); // expected to preserve stateWhenNotNull from both ?.b(out x) and ?.c(out y) // but not accesses in nested expressions: // a?.b(out x, c?.d(out y)); // expected to preserve stateWhenNotNull from a?.b(out x, ...) but not from c?.d(out y) BoundExpression expr = node.AccessExpression; while (expr is BoundConditionalAccess innerCondAccess) { Debug.Assert(innerCondAccess.Receiver is not (BoundConditionalAccess or BoundConversion)); // we assume that non-conditional accesses can never contain conditional accesses from the same "chain". // that is, we never have to dig through non-conditional accesses to find and handle conditional accesses. VisitRvalue(innerCondAccess.Receiver); expr = innerCondAccess.AccessExpression; // The savedState here represents the scenario where 0 or more of the access expressions could have been evaluated. // e.g. after visiting `a?.b(x = null)?.c(x = new object())`, the "state when not null" of `x` is NotNull, but the "state when maybe null" of `x` is MaybeNull. Join(ref savedState, ref State); } Debug.Assert(expr is BoundExpression); VisitRvalue(expr); stateWhenNotNull = State; State = savedState; Join(ref State, ref stateWhenNotNull); } } public override BoundNode? VisitConditionalAccess(BoundConditionalAccess node) { VisitConditionalAccess(node, stateWhenNotNull: out _); return null; } #nullable disable public override BoundNode VisitLoweredConditionalAccess(BoundLoweredConditionalAccess node) { VisitRvalue(node.Receiver); var savedState = this.State.Clone(); VisitRvalue(node.WhenNotNull); Join(ref this.State, ref savedState); if (node.WhenNullOpt != null) { savedState = this.State.Clone(); VisitRvalue(node.WhenNullOpt); Join(ref this.State, ref savedState); } return null; } public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node) { return null; } public override BoundNode VisitComplexConditionalReceiver(BoundComplexConditionalReceiver node) { var savedState = this.State.Clone(); VisitRvalue(node.ValueTypeReceiver); Join(ref this.State, ref savedState); savedState = this.State.Clone(); VisitRvalue(node.ReferenceTypeReceiver); Join(ref this.State, ref savedState); return null; } public override BoundNode VisitSequence(BoundSequence node) { var sideEffects = node.SideEffects; if (!sideEffects.IsEmpty) { foreach (var se in sideEffects) { VisitRvalue(se); } } VisitRvalue(node.Value); return null; } public override BoundNode VisitSequencePoint(BoundSequencePoint node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitSequencePointExpression(BoundSequencePointExpression node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitSequencePointWithSpan(BoundSequencePointWithSpan node) { if (node.StatementOpt != null) { VisitStatement(node.StatementOpt); } return null; } public override BoundNode VisitStatementList(BoundStatementList node) { return VisitStatementListWorker(node); } private BoundNode VisitStatementListWorker(BoundStatementList node) { foreach (var statement in node.Statements) { VisitStatement(statement); } return null; } public override BoundNode VisitTypeOrInstanceInitializers(BoundTypeOrInstanceInitializers node) { return VisitStatementListWorker(node); } public override BoundNode VisitUnboundLambda(UnboundLambda node) { // The presence of this node suggests an error was detected in an earlier phase. return VisitLambda(node.BindForErrorRecovery()); } public override BoundNode VisitBreakStatement(BoundBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitContinueStatement(BoundContinueStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } public override BoundNode VisitUnconvertedConditionalOperator(BoundUnconvertedConditionalOperator node) { return VisitConditionalOperatorCore(node, isByRef: false, node.Condition, node.Consequence, node.Alternative); } public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { return VisitConditionalOperatorCore(node, node.IsRef, node.Condition, node.Consequence, node.Alternative); } #nullable enable protected virtual BoundNode? VisitConditionalOperatorCore( BoundExpression node, bool isByRef, BoundExpression condition, BoundExpression consequence, BoundExpression alternative) { VisitCondition(condition); var consequenceState = this.StateWhenTrue; var alternativeState = this.StateWhenFalse; if (IsConstantTrue(condition)) { VisitConditionalOperand(alternativeState, alternative, isByRef); VisitConditionalOperand(consequenceState, consequence, isByRef); } else if (IsConstantFalse(condition)) { VisitConditionalOperand(consequenceState, consequence, isByRef); VisitConditionalOperand(alternativeState, alternative, isByRef); } else { // at this point, the state is conditional after a conditional expression if: // 1. the state is conditional after the consequence, or // 2. the state is conditional after the alternative VisitConditionalOperand(consequenceState, consequence, isByRef); var conditionalAfterConsequence = IsConditionalState; var (afterConsequenceWhenTrue, afterConsequenceWhenFalse) = conditionalAfterConsequence ? (StateWhenTrue, StateWhenFalse) : (State, State); VisitConditionalOperand(alternativeState, alternative, isByRef); if (!conditionalAfterConsequence && !IsConditionalState) { // simplify in the common case Join(ref this.State, ref afterConsequenceWhenTrue); } else { Split(); Join(ref this.StateWhenTrue, ref afterConsequenceWhenTrue); Join(ref this.StateWhenFalse, ref afterConsequenceWhenFalse); } } return null; } #nullable disable private void VisitConditionalOperand(TLocalState state, BoundExpression operand, bool isByRef) { SetState(state); if (isByRef) { VisitLvalue(operand); // exposing ref is a potential write WriteArgument(operand, RefKind.Ref, method: null); } else { Visit(operand); } } public override BoundNode VisitBaseReference(BoundBaseReference node) { return null; } public override BoundNode VisitDoStatement(BoundDoStatement node) { // do { statements; node.ContinueLabel: } while (node.Condition) node.BreakLabel: LoopHead(node); VisitStatement(node.Body); ResolveContinues(node.ContinueLabel); VisitCondition(node.Condition); TLocalState breakState = this.StateWhenFalse; SetState(this.StateWhenTrue); LoopTail(node); ResolveBreaks(breakState, node.BreakLabel); return null; } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, node.Label)); SetUnreachable(); return null; } protected void VisitLabel(LabelSymbol label, BoundStatement node) { node.AssertIsLabeledStatementWithLabel(label); ResolveBranches(label, node); var state = LabelState(label); Join(ref this.State, ref state); _labels[label] = this.State.Clone(); _labelsSeen.Add(node); } protected virtual void VisitLabel(BoundLabeledStatement node) { VisitLabel(node.Label, node); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { VisitLabel(node.Label, node); return null; } public override BoundNode VisitLabeledStatement(BoundLabeledStatement node) { VisitLabel(node); VisitStatement(node.Body); return null; } public override BoundNode VisitLockStatement(BoundLockStatement node) { VisitRvalue(node.Argument); VisitStatement(node.Body); return null; } public override BoundNode VisitNoOpStatement(BoundNoOpStatement node) { return null; } public override BoundNode VisitNamespaceExpression(BoundNamespaceExpression node) { return null; } public override BoundNode VisitUsingStatement(BoundUsingStatement node) { if (node.ExpressionOpt != null) { VisitRvalue(node.ExpressionOpt); } if (node.DeclarationsOpt != null) { VisitStatement(node.DeclarationsOpt); } VisitStatement(node.Body); if (AwaitUsingAndForeachAddsPendingBranch && node.AwaitOpt != null) { PendingBranches.Add(new PendingBranch(node, this.State, null)); } return null; } public abstract bool AwaitUsingAndForeachAddsPendingBranch { get; } public override BoundNode VisitFixedStatement(BoundFixedStatement node) { VisitStatement(node.Declarations); VisitStatement(node.Body); return null; } public override BoundNode VisitFixedLocalCollectionInitializer(BoundFixedLocalCollectionInitializer node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { BoundExpression expr = node.ExpressionOpt; VisitRvalue(expr); SetUnreachable(); return null; } public override BoundNode VisitYieldBreakStatement(BoundYieldBreakStatement node) { Debug.Assert(!this.IsConditionalState); PendingBranches.Add(new PendingBranch(node, this.State, null)); SetUnreachable(); return null; } public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) { VisitRvalue(node.Expression); PendingBranches.Add(new PendingBranch(node, this.State, null)); return null; } public override BoundNode VisitDefaultLiteral(BoundDefaultLiteral node) { return null; } public override BoundNode VisitDefaultExpression(BoundDefaultExpression node) { return null; } public override BoundNode VisitUnconvertedObjectCreationExpression(BoundUnconvertedObjectCreationExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitTypeOfOperator(BoundTypeOfOperator node) { VisitTypeExpression(node.SourceType); return null; } public override BoundNode VisitNameOfOperator(BoundNameOfOperator node) { var savedState = this.State; SetState(UnreachableState()); Visit(node.Argument); SetState(savedState); return null; } public override BoundNode VisitAddressOfOperator(BoundAddressOfOperator node) { VisitAddressOfOperand(node.Operand, shouldReadOperand: false); return null; } protected void VisitAddressOfOperand(BoundExpression operand, bool shouldReadOperand) { if (shouldReadOperand) { this.VisitRvalue(operand); } else { this.VisitLvalue(operand); } this.WriteArgument(operand, RefKind.Out, null); //Out because we know it will definitely be assigned. } public override BoundNode VisitPointerIndirectionOperator(BoundPointerIndirectionOperator node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess node) { VisitRvalue(node.Expression); VisitRvalue(node.Index); return null; } public override BoundNode VisitSizeOfOperator(BoundSizeOfOperator node) { return null; } private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase node) { VisitRvalue(node.Count); if (node.InitializerOpt != null && !node.InitializerOpt.Initializers.IsDefault) { foreach (var element in node.InitializerOpt.Initializers) { VisitRvalue(element); } } return null; } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { return VisitStackAllocArrayCreationBase(node); } public override BoundNode VisitAnonymousObjectCreationExpression(BoundAnonymousObjectCreationExpression node) { // visit arguments as r-values VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.Constructor); return null; } public override BoundNode VisitArrayLength(BoundArrayLength node) { VisitRvalue(node.Expression); return null; } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { VisitCondition(node.Condition); Debug.Assert(this.IsConditionalState); if (node.JumpIfTrue) { PendingBranches.Add(new PendingBranch(node, this.StateWhenTrue, node.Label)); this.SetState(this.StateWhenFalse); } else { PendingBranches.Add(new PendingBranch(node, this.StateWhenFalse, node.Label)); this.SetState(this.StateWhenTrue); } return null; } public override BoundNode VisitObjectInitializerExpression(BoundObjectInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } public override BoundNode VisitCollectionInitializerExpression(BoundCollectionInitializerExpression node) { return VisitObjectOrCollectionInitializerExpression(node.Initializers); } private BoundNode VisitObjectOrCollectionInitializerExpression(ImmutableArray<BoundExpression> initializers) { foreach (var initializer in initializers) { VisitRvalue(initializer); } return null; } public override BoundNode VisitObjectInitializerMember(BoundObjectInitializerMember node) { var arguments = node.Arguments; if (!arguments.IsDefaultOrEmpty) { MethodSymbol method = null; if (node.MemberSymbol?.Kind == SymbolKind.Property) { var property = (PropertySymbol)node.MemberSymbol; method = GetReadMethod(property); } VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, method); } return null; } public override BoundNode VisitDynamicObjectInitializerMember(BoundDynamicObjectInitializerMember node) { return null; } public override BoundNode VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { if (node.AddMethod.CallsAreOmitted(node.SyntaxTree)) { // If the underlying add method is a partial method without a definition, or is a conditional method // whose condition is not true, then the call has no effect and it is ignored for the purposes of // flow analysis. TLocalState savedState = savedState = this.State.Clone(); SetUnreachable(); VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); this.State = savedState; } else { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), node.AddMethod); } return null; } public override BoundNode VisitDynamicCollectionElementInitializer(BoundDynamicCollectionElementInitializer node) { VisitArguments(node.Arguments, default(ImmutableArray<RefKind>), method: null); return null; } public override BoundNode VisitImplicitReceiver(BoundImplicitReceiver node) { return null; } public override BoundNode VisitFieldEqualsValue(BoundFieldEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitPropertyEqualsValue(BoundPropertyEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitParameterEqualsValue(BoundParameterEqualsValue node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeconstructValuePlaceholder(BoundDeconstructValuePlaceholder node) { return null; } public override BoundNode VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { return null; } public override BoundNode VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { return null; } public sealed override BoundNode VisitOutVariablePendingInference(OutVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public sealed override BoundNode VisitDeconstructionVariablePendingInference(DeconstructionVariablePendingInference node) { throw ExceptionUtilities.Unreachable; } public override BoundNode VisitDiscardExpression(BoundDiscardExpression node) { return null; } private static MethodSymbol GetReadMethod(PropertySymbol property) => property.GetOwnOrInheritedGetMethod() ?? property.SetMethod; private static MethodSymbol GetWriteMethod(PropertySymbol property) => property.GetOwnOrInheritedSetMethod() ?? property.GetMethod; public override BoundNode VisitConstructorMethodBody(BoundConstructorMethodBody node) { Visit(node.Initializer); VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNonConstructorMethodBody(BoundNonConstructorMethodBody node) { VisitMethodBodies(node.BlockBody, node.ExpressionBody); return null; } public override BoundNode VisitNullCoalescingAssignmentOperator(BoundNullCoalescingAssignmentOperator node) { TLocalState leftState; if (RegularPropertyAccess(node.LeftOperand) && (BoundPropertyAccess)node.LeftOperand is var left && left.PropertySymbol is var property && property.RefKind == RefKind.None) { var readMethod = property.GetOwnOrInheritedGetMethod(); VisitReceiverBeforeCall(left.ReceiverOpt, readMethod); VisitReceiverAfterCall(left.ReceiverOpt, readMethod); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, left); } else { VisitRvalue(node.LeftOperand, isKnownToBeAnLvalue: true); var savedState = this.State.Clone(); AdjustStateForNullCoalescingAssignmentNonNullCase(node); leftState = this.State.Clone(); SetState(savedState); VisitAssignmentOfNullCoalescingAssignment(node, propertyAccessOpt: null); } Join(ref this.State, ref leftState); return null; } public override BoundNode VisitReadOnlySpanFromArray(BoundReadOnlySpanFromArray node) { VisitRvalue(node.Operand); return null; } public override BoundNode VisitFunctionPointerInvocation(BoundFunctionPointerInvocation node) { Visit(node.InvokedExpression); VisitArguments(node.Arguments, node.ArgumentRefKindsOpt, node.FunctionPointer.Signature); return null; } public override BoundNode VisitUnconvertedAddressOfOperator(BoundUnconvertedAddressOfOperator node) { // This is not encountered in correct programs, but can be seen if the function pointer was // unable to be converted and the semantic model is used to query for information. Visit(node.Operand); return null; } /// <summary> /// This visitor represents just the assignment part of the null coalescing assignment /// operator. /// </summary> protected virtual void VisitAssignmentOfNullCoalescingAssignment( BoundNullCoalescingAssignmentOperator node, BoundPropertyAccess propertyAccessOpt) { VisitRvalue(node.RightOperand); if (propertyAccessOpt != null) { var symbol = propertyAccessOpt.PropertySymbol; var writeMethod = symbol.GetOwnOrInheritedSetMethod(); PropertySetter(node, propertyAccessOpt.ReceiverOpt, writeMethod); } } public override BoundNode VisitSavePreviousSequencePoint(BoundSavePreviousSequencePoint node) { return null; } public override BoundNode VisitRestorePreviousSequencePoint(BoundRestorePreviousSequencePoint node) { return null; } public override BoundNode VisitStepThroughSequencePoint(BoundStepThroughSequencePoint node) { return null; } /// <summary> /// This visitor represents just the non-assignment part of the null coalescing assignment /// operator (when the left operand is non-null). /// </summary> protected virtual void AdjustStateForNullCoalescingAssignmentNonNullCase(BoundNullCoalescingAssignmentOperator node) { } private void VisitMethodBodies(BoundBlock blockBody, BoundBlock expressionBody) { if (blockBody == null) { Visit(expressionBody); return; } else if (expressionBody == null) { Visit(blockBody); return; } // In error cases we have two bodies. These are two unrelated pieces of code, // they are not executed one after another. As we don't really know which one the developer // intended to use, we need to visit both. We are going to pretend that there is // an unconditional fork in execution and then we are converging after each body is executed. // For example, if only one body assigns an out parameter, then after visiting both bodies // we should consider that parameter is not definitely assigned. // Note, that today this code is not executed for regular definite assignment analysis. It is // only executed for region analysis. TLocalState initialState = this.State.Clone(); Visit(blockBody); TLocalState afterBlock = this.State; SetState(initialState); Visit(expressionBody); Join(ref this.State, ref afterBlock); } #endregion visitors } /// <summary> /// The possible places that we are processing when there is a region. /// </summary> /// <remarks> /// This should be nested inside <see cref="AbstractFlowPass{TLocalState, TLocalFunctionState}"/> but is not due to https://github.com/dotnet/roslyn/issues/36992 . /// </remarks> internal enum RegionPlace { Before, Inside, After }; }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Test/Core/Compilation/TestStrongNameFileSystem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { internal sealed class TestStrongNameFileSystem : StrongNameFileSystem { internal Func<string, byte[]> ReadAllBytesFunc { get; set; } internal Func<string, FileMode, FileAccess, FileShare, FileStream> CreateFileStreamFunc { get; set; } internal TestStrongNameFileSystem() { ReadAllBytesFunc = base.ReadAllBytes; CreateFileStreamFunc = base.CreateFileStream; } internal override byte[] ReadAllBytes(string fullPath) => ReadAllBytesFunc(fullPath); internal override FileStream CreateFileStream(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) => CreateFileStreamFunc(filePath, fileMode, fileAccess, fileShare); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { internal sealed class TestStrongNameFileSystem : StrongNameFileSystem { internal Func<string, byte[]> ReadAllBytesFunc { get; set; } internal Func<string, FileMode, FileAccess, FileShare, FileStream> CreateFileStreamFunc { get; set; } internal TestStrongNameFileSystem() { ReadAllBytesFunc = base.ReadAllBytes; CreateFileStreamFunc = base.CreateFileStream; } internal override byte[] ReadAllBytes(string fullPath) => ReadAllBytesFunc(fullPath); internal override FileStream CreateFileStream(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) => CreateFileStreamFunc(filePath, fileMode, fileAccess, fileShare); } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/Portable/Symbols/TypeCompareKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the different kinds of comparison between types. /// </summary> [Flags] internal enum TypeCompareKind { ConsiderEverything = 0, // This comparison option is temporary. All usages should be reviewed, and it should be removed. https://github.com/dotnet/roslyn/issues/31742 ConsiderEverything2 = ConsiderEverything, IgnoreCustomModifiersAndArraySizesAndLowerBounds = 1, IgnoreDynamic = 2, IgnoreTupleNames = 4, IgnoreDynamicAndTupleNames = IgnoreDynamic | IgnoreTupleNames, IgnoreNullableModifiersForReferenceTypes = 8, ObliviousNullableModifierMatchesAny = 16, IgnoreNativeIntegers = 32, // For the purposes of a few specific cases such as overload comparisons, we need to consider function pointers that only differ // by ref, in, out, or ref readonly identical. For these specific scenarios, this option is available. However, it is not in // in AllIgnoreOptions because except for these few specific cases, ignoring the RefKind is not the correct behavior. // For overloading, we disallow overloading on just the type of refness in a function pointer parameter or return type. Technically // we could emit signatures overloaded on this distinction, because we must encode the type of ref in a modreq on the appropriate // parameter in metadata, which would change the type. However, this would be inconsistent with how ref vs out vs in works on // top-level signatures today, so we disallow it in source. FunctionPointerRefMatchesOutInRefReadonly = 64, AllNullableIgnoreOptions = IgnoreNullableModifiersForReferenceTypes | ObliviousNullableModifierMatchesAny, AllIgnoreOptions = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreDynamic | IgnoreTupleNames | AllNullableIgnoreOptions | IgnoreNativeIntegers, AllIgnoreOptionsForVB = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreTupleNames, CLRSignatureCompareOptions = TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the different kinds of comparison between types. /// </summary> [Flags] internal enum TypeCompareKind { ConsiderEverything = 0, // This comparison option is temporary. All usages should be reviewed, and it should be removed. https://github.com/dotnet/roslyn/issues/31742 ConsiderEverything2 = ConsiderEverything, IgnoreCustomModifiersAndArraySizesAndLowerBounds = 1, IgnoreDynamic = 2, IgnoreTupleNames = 4, IgnoreDynamicAndTupleNames = IgnoreDynamic | IgnoreTupleNames, IgnoreNullableModifiersForReferenceTypes = 8, ObliviousNullableModifierMatchesAny = 16, IgnoreNativeIntegers = 32, // For the purposes of a few specific cases such as overload comparisons, we need to consider function pointers that only differ // by ref, in, out, or ref readonly identical. For these specific scenarios, this option is available. However, it is not in // in AllIgnoreOptions because except for these few specific cases, ignoring the RefKind is not the correct behavior. // For overloading, we disallow overloading on just the type of refness in a function pointer parameter or return type. Technically // we could emit signatures overloaded on this distinction, because we must encode the type of ref in a modreq on the appropriate // parameter in metadata, which would change the type. However, this would be inconsistent with how ref vs out vs in works on // top-level signatures today, so we disallow it in source. FunctionPointerRefMatchesOutInRefReadonly = 64, AllNullableIgnoreOptions = IgnoreNullableModifiersForReferenceTypes | ObliviousNullableModifierMatchesAny, AllIgnoreOptions = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreDynamic | IgnoreTupleNames | AllNullableIgnoreOptions | IgnoreNativeIntegers, AllIgnoreOptionsForVB = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreTupleNames, CLRSignatureCompareOptions = TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds, } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/Core/Portable/RQName/Nodes/RQMemberParameterIndexFromPartialImplementation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQMemberParameterIndexFromPartialImplementation : RQMemberParameterIndex { public RQMemberParameterIndexFromPartialImplementation( RQMember containingMember, int parameterIndex) : base(containingMember, parameterIndex) { } protected override void AppendChildren(List<SimpleTreeNode> childList) { childList.Add(ContainingMember.ToSimpleTree()); childList.Add(new SimpleLeafNode(ParameterIndex.ToString())); childList.Add(new SimpleLeafNode(RQNameStrings.PartialImplementation)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQMemberParameterIndexFromPartialImplementation : RQMemberParameterIndex { public RQMemberParameterIndexFromPartialImplementation( RQMember containingMember, int parameterIndex) : base(containingMember, parameterIndex) { } protected override void AppendChildren(List<SimpleTreeNode> childList) { childList.Add(ContainingMember.ToSimpleTree()); childList.Add(new SimpleLeafNode(ParameterIndex.ToString())); childList.Add(new SimpleLeafNode(RQNameStrings.PartialImplementation)); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/TupleExpansion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using System.Collections.ObjectModel; using System.Diagnostics; using FieldInfo = Microsoft.VisualStudio.Debugger.Metadata.FieldInfo; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class TupleExpansion : Expansion { internal static TupleExpansion CreateExpansion( DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, int cardinality) { if (value.IsNull) { // No expansion. return null; } bool useRawView = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0; return new TupleExpansion(new TypeAndCustomInfo(value.Type, declaredTypeAndInfo.Info), cardinality, useRawView); } private readonly TypeAndCustomInfo _typeAndInfo; private readonly int _cardinality; private readonly bool _useRawView; private Fields _lazyFields; private TupleExpansion(TypeAndCustomInfo typeAndInfo, int cardinality, bool useRawView) { _typeAndInfo = typeAndInfo; _cardinality = cardinality; _useRawView = useRawView; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResult> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { var fields = GetFields(); var defaultView = fields.DefaultView; int startIndex2; int count2; GetIntersection(startIndex, count, index, defaultView.Count, out startIndex2, out count2); int offset = startIndex2 - index; for (int i = 0; i < count2; i++) { var row = GetMemberRow(resultProvider, inspectionContext, value, defaultView[i + offset], parent, _cardinality); rows.Add(row); } index += defaultView.Count; if (fields.IncludeRawView) { if (InRange(startIndex, count, index)) { rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext, parent, value)); } index++; } } private static EvalResult GetMemberRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, DkmClrValue value, Field field, EvalResultDataItem parent, int cardinality) { var fullNameProvider = resultProvider.FullNameProvider; var parentFullName = parent.ChildFullNamePrefix; if (parentFullName != null) { if (parent.ChildShouldParenthesize) { parentFullName = parentFullName.Parenthesize(); } var parentRuntimeType = parent.Value.Type; if (!parent.DeclaredTypeAndInfo.Type.Equals(parentRuntimeType.GetLmrType())) { parentFullName = fullNameProvider.GetClrCastExpression( inspectionContext, parentFullName, parentRuntimeType, customTypeInfo: null, castExpressionOptions: DkmClrCastExpressionOptions.ParenthesizeEntireExpression); } } // Ideally if the caller requests multiple items in a nested tuple // we should only evaluate Rest once, and should only calculate // the full name for Rest once. string fullName; var fieldValue = GetValueAndFullName( fullNameProvider, inspectionContext, value, field, parentFullName, out fullName); var name = field.Name; var typeDeclaringMemberAndInfo = default(TypeAndCustomInfo); var declaredTypeAndInfo = field.FieldTypeAndInfo; var flags = fieldValue.EvalFlags; var formatSpecifiers = Formatter.NoFormatSpecifiers; if (field.IsRest) { var displayValue = fieldValue.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); var displayType = ResultProvider.GetTypeName( inspectionContext, fieldValue, declaredTypeAndInfo.ClrType, declaredTypeAndInfo.Info, isPointerDereference: false); var expansion = new TupleExpansion(declaredTypeAndInfo, cardinality - (TypeHelpers.TupleFieldRestPosition - 1), useRawView: true); return new EvalResult( ExpansionKind.Explicit, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, useDebuggerDisplay: false, value: fieldValue, displayValue: displayValue, expansion: expansion, childShouldParenthesize: false, fullName: fullName, childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers: Formatter.AddFormatSpecifier(formatSpecifiers, "raw"), category: DkmEvaluationResultCategory.Other, flags: flags, editableValue: null, inspectionContext: inspectionContext, displayName: name, displayType: displayType); } return resultProvider.CreateDataItem( inspectionContext, name, typeDeclaringMemberAndInfo: typeDeclaringMemberAndInfo, declaredTypeAndInfo: declaredTypeAndInfo, value: fieldValue, useDebuggerDisplay: false, expansionFlags: ExpansionFlags.All, childShouldParenthesize: false, fullName: fullName, formatSpecifiers: formatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: flags, evalFlags: DkmEvaluationFlags.None, canFavorite: false, isFavorite: false, supportsFavorites: true); } private static DkmClrValue GetValueAndFullName( IDkmClrFullNameProvider fullNameProvider, DkmInspectionContext inspectionContext, DkmClrValue value, Field field, string parentFullName, out string fullName) { var parent = field.Parent; if (parent != null) { value = GetValueAndFullName( fullNameProvider, inspectionContext, value, parent, parentFullName, out parentFullName); } var fieldName = field.FieldInfo.Name; fullName = (parentFullName == null) ? null : fullNameProvider.GetClrMemberName( inspectionContext, parentFullName, clrType: field.DeclaringTypeAndInfo.ClrType, customTypeInfo: null, memberName: fieldName, requiresExplicitCast: false, isStatic: false); return value.GetFieldValue(fieldName, inspectionContext); } private sealed class Field { internal readonly TypeAndCustomInfo DeclaringTypeAndInfo; internal readonly TypeAndCustomInfo FieldTypeAndInfo; internal readonly FieldInfo FieldInfo; // type field internal readonly string Name; internal readonly Field Parent; // parent Rest field, if any internal readonly bool IsRest; internal Field( TypeAndCustomInfo declaringTypeAndInfo, TypeAndCustomInfo fieldTypeAndInfo, FieldInfo fieldInfo, string name, Field parent, bool isRest) { Debug.Assert(declaringTypeAndInfo.ClrType != null); Debug.Assert(fieldTypeAndInfo.ClrType != null); Debug.Assert(fieldInfo != null); Debug.Assert(name != null); Debug.Assert(declaringTypeAndInfo.Type.Equals(fieldInfo.DeclaringType)); Debug.Assert(fieldTypeAndInfo.Type.Equals(fieldInfo.FieldType)); Debug.Assert(parent == null || parent.FieldInfo.FieldType.Equals(fieldInfo.DeclaringType)); DeclaringTypeAndInfo = declaringTypeAndInfo; FieldTypeAndInfo = fieldTypeAndInfo; FieldInfo = fieldInfo; Name = name; Parent = parent; IsRest = isRest; } } private sealed class Fields { internal readonly ReadOnlyCollection<Field> DefaultView; internal readonly bool IncludeRawView; internal Fields(ReadOnlyCollection<Field> defaultView, bool includeRawView) { DefaultView = defaultView; IncludeRawView = includeRawView; } } private Fields GetFields() { if (_lazyFields == null) { _lazyFields = GetFields(_typeAndInfo, _cardinality, _useRawView); } return _lazyFields; } private static Fields GetFields(TypeAndCustomInfo declaringTypeAndInfo, int cardinality, bool useRawView) { Debug.Assert(declaringTypeAndInfo.Type.GetTupleCardinalityIfAny() == cardinality); var appDomain = declaringTypeAndInfo.ClrType.AppDomain; var customTypeInfoMap = CustomTypeInfoTypeArgumentMap.Create(declaringTypeAndInfo); var tupleElementNames = customTypeInfoMap.TupleElementNames; var builder = ArrayBuilder<Field>.GetInstance(); Field parent = null; int offset = 0; bool includeRawView = false; while (true) { var declaringType = declaringTypeAndInfo.Type; int n = Math.Min(cardinality, TypeHelpers.TupleFieldRestPosition - 1); for (int index = 0; index < n; index++) { var fieldName = TypeHelpers.GetTupleFieldName(index); var field = declaringType.GetTupleField(fieldName); if (field == null) { // Ignore missing fields. continue; } var fieldTypeAndInfo = GetTupleFieldTypeAndInfo(appDomain, field, customTypeInfoMap); if (!useRawView) { var name = CustomTypeInfo.GetTupleElementNameIfAny(tupleElementNames, offset + index); if (name != null) { includeRawView = true; builder.Add(new Field(declaringTypeAndInfo, fieldTypeAndInfo, field, name, parent, isRest: false)); continue; } } builder.Add(new Field( declaringTypeAndInfo, fieldTypeAndInfo, field, (offset == 0) ? fieldName : TypeHelpers.GetTupleFieldName(offset + index), parent, isRest: false)); } cardinality -= n; if (cardinality == 0) { break; } var rest = declaringType.GetTupleField(TypeHelpers.TupleFieldRestName); if (rest == null) { // Ignore remaining fields. break; } var restTypeAndInfo = GetTupleFieldTypeAndInfo(appDomain, rest, customTypeInfoMap); var restField = new Field(declaringTypeAndInfo, restTypeAndInfo, rest, TypeHelpers.TupleFieldRestName, parent, isRest: true); if (useRawView) { builder.Add(restField); break; } includeRawView = true; parent = restField; declaringTypeAndInfo = restTypeAndInfo; offset += TypeHelpers.TupleFieldRestPosition - 1; } return new Fields(builder.ToImmutableAndFree(), includeRawView); } private static TypeAndCustomInfo GetTupleFieldTypeAndInfo( DkmClrAppDomain appDomain, FieldInfo field, CustomTypeInfoTypeArgumentMap customTypeInfoMap) { var declaringTypeDef = field.DeclaringType.GetGenericTypeDefinition(); var fieldDef = declaringTypeDef.GetTupleField(field.Name); var fieldType = DkmClrType.Create(appDomain, field.FieldType); var fieldTypeInfo = customTypeInfoMap.SubstituteCustomTypeInfo(fieldDef.FieldType, null); return new TypeAndCustomInfo(fieldType, fieldTypeInfo); } private EvalResult CreateRawViewRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value) { var displayName = Resources.RawView; var displayValue = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); var displayType = ResultProvider.GetTypeName( inspectionContext, value, _typeAndInfo.ClrType, _typeAndInfo.Info, isPointerDereference: false); var expansion = new TupleExpansion(_typeAndInfo, _cardinality, useRawView: true); return new EvalResult( ExpansionKind.Explicit, displayName, default(TypeAndCustomInfo), _typeAndInfo, useDebuggerDisplay: false, value: value, displayValue: displayValue, expansion: expansion, childShouldParenthesize: parent.ChildShouldParenthesize, fullName: parent.FullNameWithoutFormatSpecifiers, childFullNamePrefixOpt: parent.ChildFullNamePrefix, formatSpecifiers: Formatter.AddFormatSpecifier(parent.FormatSpecifiers, "raw"), category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext, displayName: displayName, displayType: displayType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using System.Collections.ObjectModel; using System.Diagnostics; using FieldInfo = Microsoft.VisualStudio.Debugger.Metadata.FieldInfo; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class TupleExpansion : Expansion { internal static TupleExpansion CreateExpansion( DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, int cardinality) { if (value.IsNull) { // No expansion. return null; } bool useRawView = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0; return new TupleExpansion(new TypeAndCustomInfo(value.Type, declaredTypeAndInfo.Info), cardinality, useRawView); } private readonly TypeAndCustomInfo _typeAndInfo; private readonly int _cardinality; private readonly bool _useRawView; private Fields _lazyFields; private TupleExpansion(TypeAndCustomInfo typeAndInfo, int cardinality, bool useRawView) { _typeAndInfo = typeAndInfo; _cardinality = cardinality; _useRawView = useRawView; } internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResult> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { var fields = GetFields(); var defaultView = fields.DefaultView; int startIndex2; int count2; GetIntersection(startIndex, count, index, defaultView.Count, out startIndex2, out count2); int offset = startIndex2 - index; for (int i = 0; i < count2; i++) { var row = GetMemberRow(resultProvider, inspectionContext, value, defaultView[i + offset], parent, _cardinality); rows.Add(row); } index += defaultView.Count; if (fields.IncludeRawView) { if (InRange(startIndex, count, index)) { rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext, parent, value)); } index++; } } private static EvalResult GetMemberRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, DkmClrValue value, Field field, EvalResultDataItem parent, int cardinality) { var fullNameProvider = resultProvider.FullNameProvider; var parentFullName = parent.ChildFullNamePrefix; if (parentFullName != null) { if (parent.ChildShouldParenthesize) { parentFullName = parentFullName.Parenthesize(); } var parentRuntimeType = parent.Value.Type; if (!parent.DeclaredTypeAndInfo.Type.Equals(parentRuntimeType.GetLmrType())) { parentFullName = fullNameProvider.GetClrCastExpression( inspectionContext, parentFullName, parentRuntimeType, customTypeInfo: null, castExpressionOptions: DkmClrCastExpressionOptions.ParenthesizeEntireExpression); } } // Ideally if the caller requests multiple items in a nested tuple // we should only evaluate Rest once, and should only calculate // the full name for Rest once. string fullName; var fieldValue = GetValueAndFullName( fullNameProvider, inspectionContext, value, field, parentFullName, out fullName); var name = field.Name; var typeDeclaringMemberAndInfo = default(TypeAndCustomInfo); var declaredTypeAndInfo = field.FieldTypeAndInfo; var flags = fieldValue.EvalFlags; var formatSpecifiers = Formatter.NoFormatSpecifiers; if (field.IsRest) { var displayValue = fieldValue.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); var displayType = ResultProvider.GetTypeName( inspectionContext, fieldValue, declaredTypeAndInfo.ClrType, declaredTypeAndInfo.Info, isPointerDereference: false); var expansion = new TupleExpansion(declaredTypeAndInfo, cardinality - (TypeHelpers.TupleFieldRestPosition - 1), useRawView: true); return new EvalResult( ExpansionKind.Explicit, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, useDebuggerDisplay: false, value: fieldValue, displayValue: displayValue, expansion: expansion, childShouldParenthesize: false, fullName: fullName, childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers: Formatter.AddFormatSpecifier(formatSpecifiers, "raw"), category: DkmEvaluationResultCategory.Other, flags: flags, editableValue: null, inspectionContext: inspectionContext, displayName: name, displayType: displayType); } return resultProvider.CreateDataItem( inspectionContext, name, typeDeclaringMemberAndInfo: typeDeclaringMemberAndInfo, declaredTypeAndInfo: declaredTypeAndInfo, value: fieldValue, useDebuggerDisplay: false, expansionFlags: ExpansionFlags.All, childShouldParenthesize: false, fullName: fullName, formatSpecifiers: formatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: flags, evalFlags: DkmEvaluationFlags.None, canFavorite: false, isFavorite: false, supportsFavorites: true); } private static DkmClrValue GetValueAndFullName( IDkmClrFullNameProvider fullNameProvider, DkmInspectionContext inspectionContext, DkmClrValue value, Field field, string parentFullName, out string fullName) { var parent = field.Parent; if (parent != null) { value = GetValueAndFullName( fullNameProvider, inspectionContext, value, parent, parentFullName, out parentFullName); } var fieldName = field.FieldInfo.Name; fullName = (parentFullName == null) ? null : fullNameProvider.GetClrMemberName( inspectionContext, parentFullName, clrType: field.DeclaringTypeAndInfo.ClrType, customTypeInfo: null, memberName: fieldName, requiresExplicitCast: false, isStatic: false); return value.GetFieldValue(fieldName, inspectionContext); } private sealed class Field { internal readonly TypeAndCustomInfo DeclaringTypeAndInfo; internal readonly TypeAndCustomInfo FieldTypeAndInfo; internal readonly FieldInfo FieldInfo; // type field internal readonly string Name; internal readonly Field Parent; // parent Rest field, if any internal readonly bool IsRest; internal Field( TypeAndCustomInfo declaringTypeAndInfo, TypeAndCustomInfo fieldTypeAndInfo, FieldInfo fieldInfo, string name, Field parent, bool isRest) { Debug.Assert(declaringTypeAndInfo.ClrType != null); Debug.Assert(fieldTypeAndInfo.ClrType != null); Debug.Assert(fieldInfo != null); Debug.Assert(name != null); Debug.Assert(declaringTypeAndInfo.Type.Equals(fieldInfo.DeclaringType)); Debug.Assert(fieldTypeAndInfo.Type.Equals(fieldInfo.FieldType)); Debug.Assert(parent == null || parent.FieldInfo.FieldType.Equals(fieldInfo.DeclaringType)); DeclaringTypeAndInfo = declaringTypeAndInfo; FieldTypeAndInfo = fieldTypeAndInfo; FieldInfo = fieldInfo; Name = name; Parent = parent; IsRest = isRest; } } private sealed class Fields { internal readonly ReadOnlyCollection<Field> DefaultView; internal readonly bool IncludeRawView; internal Fields(ReadOnlyCollection<Field> defaultView, bool includeRawView) { DefaultView = defaultView; IncludeRawView = includeRawView; } } private Fields GetFields() { if (_lazyFields == null) { _lazyFields = GetFields(_typeAndInfo, _cardinality, _useRawView); } return _lazyFields; } private static Fields GetFields(TypeAndCustomInfo declaringTypeAndInfo, int cardinality, bool useRawView) { Debug.Assert(declaringTypeAndInfo.Type.GetTupleCardinalityIfAny() == cardinality); var appDomain = declaringTypeAndInfo.ClrType.AppDomain; var customTypeInfoMap = CustomTypeInfoTypeArgumentMap.Create(declaringTypeAndInfo); var tupleElementNames = customTypeInfoMap.TupleElementNames; var builder = ArrayBuilder<Field>.GetInstance(); Field parent = null; int offset = 0; bool includeRawView = false; while (true) { var declaringType = declaringTypeAndInfo.Type; int n = Math.Min(cardinality, TypeHelpers.TupleFieldRestPosition - 1); for (int index = 0; index < n; index++) { var fieldName = TypeHelpers.GetTupleFieldName(index); var field = declaringType.GetTupleField(fieldName); if (field == null) { // Ignore missing fields. continue; } var fieldTypeAndInfo = GetTupleFieldTypeAndInfo(appDomain, field, customTypeInfoMap); if (!useRawView) { var name = CustomTypeInfo.GetTupleElementNameIfAny(tupleElementNames, offset + index); if (name != null) { includeRawView = true; builder.Add(new Field(declaringTypeAndInfo, fieldTypeAndInfo, field, name, parent, isRest: false)); continue; } } builder.Add(new Field( declaringTypeAndInfo, fieldTypeAndInfo, field, (offset == 0) ? fieldName : TypeHelpers.GetTupleFieldName(offset + index), parent, isRest: false)); } cardinality -= n; if (cardinality == 0) { break; } var rest = declaringType.GetTupleField(TypeHelpers.TupleFieldRestName); if (rest == null) { // Ignore remaining fields. break; } var restTypeAndInfo = GetTupleFieldTypeAndInfo(appDomain, rest, customTypeInfoMap); var restField = new Field(declaringTypeAndInfo, restTypeAndInfo, rest, TypeHelpers.TupleFieldRestName, parent, isRest: true); if (useRawView) { builder.Add(restField); break; } includeRawView = true; parent = restField; declaringTypeAndInfo = restTypeAndInfo; offset += TypeHelpers.TupleFieldRestPosition - 1; } return new Fields(builder.ToImmutableAndFree(), includeRawView); } private static TypeAndCustomInfo GetTupleFieldTypeAndInfo( DkmClrAppDomain appDomain, FieldInfo field, CustomTypeInfoTypeArgumentMap customTypeInfoMap) { var declaringTypeDef = field.DeclaringType.GetGenericTypeDefinition(); var fieldDef = declaringTypeDef.GetTupleField(field.Name); var fieldType = DkmClrType.Create(appDomain, field.FieldType); var fieldTypeInfo = customTypeInfoMap.SubstituteCustomTypeInfo(fieldDef.FieldType, null); return new TypeAndCustomInfo(fieldType, fieldTypeInfo); } private EvalResult CreateRawViewRow( ResultProvider resultProvider, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value) { var displayName = Resources.RawView; var displayValue = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); var displayType = ResultProvider.GetTypeName( inspectionContext, value, _typeAndInfo.ClrType, _typeAndInfo.Info, isPointerDereference: false); var expansion = new TupleExpansion(_typeAndInfo, _cardinality, useRawView: true); return new EvalResult( ExpansionKind.Explicit, displayName, default(TypeAndCustomInfo), _typeAndInfo, useDebuggerDisplay: false, value: value, displayValue: displayValue, expansion: expansion, childShouldParenthesize: parent.ChildShouldParenthesize, fullName: parent.FullNameWithoutFormatSpecifiers, childFullNamePrefixOpt: parent.ChildFullNamePrefix, formatSpecifiers: Formatter.AddFormatSpecifier(parent.FormatSpecifiers, "raw"), category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext, displayName: displayName, displayType: displayType); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Options; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal static class GenerateEqualsAndGetHashCodeFromMembersOptions { public static readonly PerLanguageOption2<bool> GenerateOperators = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(GenerateOperators), defaultValue: false, storageLocation: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}")); public static readonly PerLanguageOption2<bool> ImplementIEquatable = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(ImplementIEquatable), defaultValue: false, storageLocation: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(ImplementIEquatable)}")); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Options; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal static class GenerateEqualsAndGetHashCodeFromMembersOptions { public static readonly PerLanguageOption2<bool> GenerateOperators = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(GenerateOperators), defaultValue: false, storageLocation: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}")); public static readonly PerLanguageOption2<bool> ImplementIEquatable = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(ImplementIEquatable), defaultValue: false, storageLocation: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(ImplementIEquatable)}")); } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal readonly struct BuildPaths { /// <summary> /// The path which contains the compiler binaries and response files. /// </summary> internal string ClientDirectory { get; } /// <summary> /// The path in which the compilation takes place. /// </summary> internal string WorkingDirectory { get; } /// <summary> /// The path which contains mscorlib. This can be null when specified by the user or running in a /// CoreClr environment. /// </summary> internal string? SdkDirectory { get; } /// <summary> /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>. The latter /// relies on global state individual compilations should ignore. /// </summary> internal string? TempDirectory { get; } internal BuildPaths(string clientDir, string workingDir, string? sdkDir, string? tempDir) { ClientDirectory = clientDir; WorkingDirectory = workingDir; SdkDirectory = sdkDir; TempDirectory = tempDir; } } /// <summary> /// Base class for csc.exe, csi.exe, vbc.exe and vbi.exe implementations. /// </summary> internal abstract partial class CommonCompiler { internal const int Failed = 1; internal const int Succeeded = 0; /// <summary> /// Fallback encoding that is lazily retrieved if needed. If <see cref="EncodedStringText.CreateFallbackEncoding"/> is /// evaluated and stored, the value is used if a PDB is created for this compilation. /// </summary> private readonly Lazy<Encoding> _fallbackEncoding = new Lazy<Encoding>(EncodedStringText.CreateFallbackEncoding); public CommonMessageProvider MessageProvider { get; } public CommandLineArguments Arguments { get; } public IAnalyzerAssemblyLoader AssemblyLoader { get; private set; } public GeneratorDriverCache? GeneratorDriverCache { get; } public abstract DiagnosticFormatter DiagnosticFormatter { get; } /// <summary> /// The set of source file paths that are in the set of embedded paths. /// This is used to prevent reading source files that are embedded twice. /// </summary> public IReadOnlySet<string> EmbeddedSourcePaths { get; } /// <summary> /// The <see cref="ICommonCompilerFileSystem"/> used to access the file system inside this instance. /// </summary> internal ICommonCompilerFileSystem FileSystem { get; set; } = StandardFileSystem.Instance; private readonly HashSet<Diagnostic> _reportedDiagnostics = new HashSet<Diagnostic>(); public abstract Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLoggerOpt, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions); public abstract void PrintLogo(TextWriter consoleOutput); public abstract void PrintHelp(TextWriter consoleOutput); public abstract void PrintLangVersions(TextWriter consoleOutput); /// <summary> /// Print compiler version /// </summary> /// <param name="consoleOutput"></param> public virtual void PrintVersion(TextWriter consoleOutput) { consoleOutput.WriteLine(GetCompilerVersion()); } protected abstract bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code); protected abstract void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators); public CommonCompiler(CommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader, GeneratorDriverCache? driverCache) { IEnumerable<string> allArgs = args; Debug.Assert(null == responseFile || PathUtilities.IsAbsolute(responseFile)); if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile)) { allArgs = new[] { "@" + responseFile }.Concat(allArgs); } this.Arguments = parser.Parse(allArgs, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, additionalReferenceDirectories); this.MessageProvider = parser.MessageProvider; this.AssemblyLoader = assemblyLoader; this.GeneratorDriverCache = driverCache; this.EmbeddedSourcePaths = GetEmbeddedSourcePaths(Arguments); if (Arguments.ParseOptions.Features.ContainsKey("debug-determinism")) { EmitDeterminismKey(Arguments, args, buildPaths.WorkingDirectory, parser); } } internal abstract bool SuppressDefaultResponseFile(IEnumerable<string> args); /// <summary> /// The type of the compiler class for version information in /help and /version. /// We don't simply use this.GetType() because that would break mock subclasses. /// </summary> internal abstract Type Type { get; } /// <summary> /// The version of this compiler with commit hash, used in logo and /version output. /// </summary> internal string GetCompilerVersion() { return GetProductVersion(Type); } internal static string GetProductVersion(Type type) { string? assemblyVersion = GetInformationalVersionWithoutHash(type); string? hash = GetShortCommitHash(type); return $"{assemblyVersion} ({hash})"; } [return: NotNullIfNotNull("hash")] internal static string? ExtractShortCommitHash(string? hash) { // leave "<developer build>" alone, but truncate SHA to 8 characters if (hash != null && hash.Length >= 8 && hash[0] != '<') { return hash.Substring(0, 8); } return hash; } private static string? GetInformationalVersionWithoutHash(Type type) { // The attribute stores a SemVer2-formatted string: `A.B.C(-...)?(+...)?` // We remove the section after the + (if any is present) return type.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0]; } private static string? GetShortCommitHash(Type type) { var hash = type.Assembly.GetCustomAttribute<CommitHashAttribute>()?.Hash; return ExtractShortCommitHash(hash); } /// <summary> /// Tool name used, along with assembly version, for error logging. /// </summary> internal abstract string GetToolName(); /// <summary> /// Tool version identifier used for error logging. /// </summary> internal Version? GetAssemblyVersion() { return Type.GetTypeInfo().Assembly.GetName().Version; } internal string GetCultureName() { return Culture.Name; } internal virtual Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return (path, properties) => { var peStream = FileSystem.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read); return MetadataReference.CreateFromFile(peStream, path, properties); }; } internal virtual MetadataReferenceResolver GetCommandLineMetadataReferenceResolver(TouchedFileLogger? loggerOpt) { var pathResolver = new CompilerRelativePathResolver(FileSystem, Arguments.ReferencePaths, Arguments.BaseDirectory!); return new LoggingMetadataFileReferenceResolver(pathResolver, GetMetadataProvider(), loggerOpt); } /// <summary> /// Resolves metadata references stored in command line arguments and reports errors for those that can't be resolved. /// </summary> internal List<MetadataReference> ResolveMetadataReferences( List<DiagnosticInfo> diagnostics, TouchedFileLogger? touchedFiles, out MetadataReferenceResolver referenceDirectiveResolver) { var commandLineReferenceResolver = GetCommandLineMetadataReferenceResolver(touchedFiles); List<MetadataReference> resolved = new List<MetadataReference>(); Arguments.ResolveMetadataReferences(commandLineReferenceResolver, diagnostics, this.MessageProvider, resolved); if (Arguments.IsScriptRunner) { referenceDirectiveResolver = commandLineReferenceResolver; } else { // when compiling into an assembly (csc/vbc) we only allow #r that match references given on command line: referenceDirectiveResolver = new ExistingReferencesResolver(commandLineReferenceResolver, resolved.ToImmutableArray()); } return resolved; } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics) { return TryReadFileContent(file, diagnostics, out _); } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <param name="normalizedFilePath">If given <paramref name="file"/> opens successfully, set to normalized absolute path of the file, null otherwise.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics, out string? normalizedFilePath) { var filePath = file.Path; try { if (file.IsInputRedirected) { using var data = Console.OpenStandardInput(); normalizedFilePath = filePath; return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } else { using var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedFilePath); return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } } catch (Exception e) { diagnostics.Add(ToFileReadDiagnostics(this.MessageProvider, e, filePath)); normalizedFilePath = null; return null; } } /// <summary> /// Read all analyzer config files from the given paths. /// </summary> internal bool TryGetAnalyzerConfigSet( ImmutableArray<string> analyzerConfigPaths, DiagnosticBag diagnostics, [NotNullWhen(true)] out AnalyzerConfigSet? analyzerConfigSet) { var configs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigPaths.Length); var processedDirs = PooledHashSet<string>.GetInstance(); foreach (var configPath in analyzerConfigPaths) { // The editorconfig spec requires all paths use '/' as the directory separator. // Since no known system allows directory separators as part of the file name, // we can replace every instance of the directory separator with a '/' string? fileContent = TryReadFileContent(configPath, diagnostics, out string? normalizedPath); if (fileContent is null) { // Error reading a file. Bail out and report error. break; } Debug.Assert(normalizedPath is object); var directory = Path.GetDirectoryName(normalizedPath) ?? normalizedPath; var editorConfig = AnalyzerConfig.Parse(fileContent, normalizedPath); if (!editorConfig.IsGlobal) { if (processedDirs.Contains(directory)) { diagnostics.Add(Diagnostic.Create( MessageProvider, MessageProvider.ERR_MultipleAnalyzerConfigsInSameDir, directory)); break; } processedDirs.Add(directory); } configs.Add(editorConfig); } processedDirs.Free(); if (diagnostics.HasAnyErrors()) { configs.Free(); analyzerConfigSet = null; return false; } analyzerConfigSet = AnalyzerConfigSet.Create(configs, out var setDiagnostics); diagnostics.AddRange(setDiagnostics); return true; } /// <summary> /// Returns the fallback encoding for parsing source files, if used, or null /// if not used /// </summary> internal Encoding? GetFallbackEncoding() { if (_fallbackEncoding.IsValueCreated) { return _fallbackEncoding.Value; } return null; } /// <summary> /// Read a UTF-8 encoded file and return the text as a string. /// </summary> private string? TryReadFileContent(string filePath, DiagnosticBag diagnostics, out string? normalizedPath) { try { var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedPath); using (var reader = new StreamReader(data, Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (Exception e) { diagnostics.Add(Diagnostic.Create(ToFileReadDiagnostics(MessageProvider, e, filePath))); normalizedPath = null; return null; } } private Stream OpenFileForReadWithSmallBufferOptimization(string filePath, out string normalizedFilePath) // PERF: Using a very small buffer size for the FileStream opens up an optimization within EncodedStringText/EmbeddedText where // we read the entire FileStream into a byte array in one shot. For files that are actually smaller than the buffer // size, FileStream.Read still allocates the internal buffer. => FileSystem.OpenFileEx( filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1, options: FileOptions.None, out normalizedFilePath); internal EmbeddedText? TryReadEmbeddedFileContent(string filePath, DiagnosticBag diagnostics) { try { using (var stream = OpenFileForReadWithSmallBufferOptimization(filePath, out _)) { const int LargeObjectHeapLimit = 80 * 1024; if (stream.Length < LargeObjectHeapLimit) { ArraySegment<byte> bytes; if (EncodedStringText.TryGetBytesFromStream(stream, out bytes)) { return EmbeddedText.FromBytes(filePath, bytes, Arguments.ChecksumAlgorithm); } } return EmbeddedText.FromStream(filePath, stream, Arguments.ChecksumAlgorithm); } } catch (Exception e) { diagnostics.Add(MessageProvider.CreateDiagnostic(ToFileReadDiagnostics(this.MessageProvider, e, filePath))); return null; } } private ImmutableArray<EmbeddedText?> AcquireEmbeddedTexts(Compilation compilation, DiagnosticBag diagnostics) { Debug.Assert(compilation.Options.SourceReferenceResolver is object); if (Arguments.EmbeddedFiles.IsEmpty) { return ImmutableArray<EmbeddedText?>.Empty; } var embeddedTreeMap = new Dictionary<string, SyntaxTree>(Arguments.EmbeddedFiles.Length); var embeddedFileOrderedSet = new OrderedSet<string>(Arguments.EmbeddedFiles.Select(e => e.Path)); foreach (var tree in compilation.SyntaxTrees) { // Skip trees that will not have their text embedded. if (!EmbeddedSourcePaths.Contains(tree.FilePath)) { continue; } // Skip trees with duplicated paths. (VB allows this and "first tree wins" is same as PDB emit policy.) if (embeddedTreeMap.ContainsKey(tree.FilePath)) { continue; } // map embedded file path to corresponding source tree embeddedTreeMap.Add(tree.FilePath, tree); // also embed the text of any #line directive targets of embedded tree ResolveEmbeddedFilesFromExternalSourceDirectives(tree, compilation.Options.SourceReferenceResolver, embeddedFileOrderedSet, diagnostics); } var embeddedTextBuilder = ImmutableArray.CreateBuilder<EmbeddedText?>(embeddedFileOrderedSet.Count); foreach (var path in embeddedFileOrderedSet) { SyntaxTree? tree; EmbeddedText? text; if (embeddedTreeMap.TryGetValue(path, out tree)) { text = EmbeddedText.FromSource(path, tree.GetText()); Debug.Assert(text != null); } else { text = TryReadEmbeddedFileContent(path, diagnostics); Debug.Assert(text != null || diagnostics.HasAnyErrors()); } // We can safely add nulls because result will be ignored if any error is produced. // This allows the MoveToImmutable to work below in all cases. embeddedTextBuilder.Add(text); } return embeddedTextBuilder.MoveToImmutable(); } protected abstract void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics); private static IReadOnlySet<string> GetEmbeddedSourcePaths(CommandLineArguments arguments) { if (arguments.EmbeddedFiles.IsEmpty) { return SpecializedCollections.EmptyReadOnlySet<string>(); } // Note that we require an exact match between source and embedded file paths (case-sensitive // and without normalization). If two files are the same but spelled differently, they will // be handled as separate files, meaning the embedding pass will read the content a second // time. This can also lead to more than one document entry in the PDB for the same document // if the PDB document de-duping policy in emit (normalize + case-sensitive in C#, // normalize + case-insensitive in VB) is not enough to converge them. var set = new HashSet<string>(arguments.EmbeddedFiles.Select(f => f.Path)); set.IntersectWith(arguments.SourceFiles.Select(f => f.Path)); return SpecializedCollections.StronglyTypedReadOnlySet(set); } internal static DiagnosticInfo ToFileReadDiagnostics(CommonMessageProvider messageProvider, Exception e, string filePath) { DiagnosticInfo diagnosticInfo; if (e is FileNotFoundException || e is DirectoryNotFoundException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_FileNotFound, filePath); } else if (e is InvalidDataException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_BinaryFile, filePath); } else { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_NoSourceFile, filePath, e.Message); } return diagnosticInfo; } /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<Diagnostic> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) { bool hasErrors = false; foreach (var diag in diagnostics) { reportDiagnostic(diag, compilation == null ? null : diag.GetSuppressionInfo(compilation)); } return hasErrors; // Local functions void reportDiagnostic(Diagnostic diag, SuppressionInfo? suppressionInfo) { if (_reportedDiagnostics.Contains(diag)) { // TODO: This invariant fails (at least) in the case where we see a member declaration "x = 1;". // First we attempt to parse a member declaration starting at "x". When we see the "=", we // create an IncompleteMemberSyntax with return type "x" and an error at the location of the "x". // Then we parse a member declaration starting at "=". This is an invalid member declaration start // so we attach an error to the "=" and attach it (plus following tokens) to the IncompleteMemberSyntax // we previously created. //this assert isn't valid if we change the design to not bail out after each phase. //System.Diagnostics.Debug.Assert(diag.Severity != DiagnosticSeverity.Error); return; } else if (diag.Severity == DiagnosticSeverity.Hidden) { // Not reported from the command-line compiler. return; } // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics should not be reported on the console output. errorLoggerOpt?.LogDiagnostic(diag, suppressionInfo); // If the diagnostic was suppressed by one or more DiagnosticSuppressor(s), then we report info diagnostics for each suppression // so that the suppression information is available in the binary logs and verbose build logs. if (diag.ProgrammaticSuppressionInfo != null) { foreach (var (id, justification) in diag.ProgrammaticSuppressionInfo.Suppressions) { var suppressionDiag = new SuppressionDiagnostic(diag, id, justification); if (_reportedDiagnostics.Add(suppressionDiag)) { PrintError(suppressionDiag, consoleOutput); } } _reportedDiagnostics.Add(diag); return; } if (diag.IsSuppressed) { return; } // Diagnostics that aren't suppressed will be reported to the console output and, if they are errors, // they should fail the run if (diag.Severity == DiagnosticSeverity.Error) { hasErrors = true; } PrintError(diag, consoleOutput); _reportedDiagnostics.Add(diag); } } /// <summary>Returns true if there were any errors, false otherwise.</summary> private bool ReportDiagnostics(DiagnosticBag diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.ToReadOnly(), consoleOutput, errorLoggerOpt, compilation); /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<DiagnosticInfo> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.Select(info => Diagnostic.Create(info)), consoleOutput, errorLoggerOpt, compilation); /// <summary> /// Returns true if there are any error diagnostics in the bag which cannot be suppressed and /// are guaranteed to break the build. /// Only diagnostics which have default severity error and are tagged as NotConfigurable fall in this bucket. /// This includes all compiler error diagnostics and specific analyzer error diagnostics that are marked as not configurable by the analyzer author. /// </summary> internal static bool HasUnsuppressableErrors(DiagnosticBag diagnostics) { foreach (var diag in diagnostics.AsEnumerable()) { if (diag.IsUnsuppressableError()) { return true; } } return false; } /// <summary> /// Returns true if the bag has any diagnostics with effective Severity=Error. Also returns true for warnings or informationals /// or warnings promoted to error via /warnaserror which are not suppressed. /// </summary> internal static bool HasUnsuppressedErrors(DiagnosticBag diagnostics) { foreach (Diagnostic diagnostic in diagnostics.AsEnumerable()) { if (diagnostic.IsUnsuppressedError) { return true; } } return false; } protected virtual void PrintError(Diagnostic diagnostic, TextWriter consoleOutput) { consoleOutput.WriteLine(DiagnosticFormatter.Format(diagnostic, Culture)); } public SarifErrorLogger? GetErrorLogger(TextWriter consoleOutput, CancellationToken cancellationToken) { Debug.Assert(Arguments.ErrorLogOptions?.Path != null); var diagnostics = DiagnosticBag.GetInstance(); var errorLog = OpenFile(Arguments.ErrorLogOptions.Path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); SarifErrorLogger? logger; if (errorLog == null) { Debug.Assert(diagnostics.HasAnyErrors()); logger = null; } else { string toolName = GetToolName(); string compilerVersion = GetCompilerVersion(); Version assemblyVersion = GetAssemblyVersion() ?? new Version(); if (Arguments.ErrorLogOptions.SarifVersion == SarifVersion.Sarif1) { logger = new SarifV1ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } else { logger = new SarifV2ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } } ReportDiagnostics(diagnostics.ToReadOnlyAndFree(), consoleOutput, errorLoggerOpt: logger, compilation: null); return logger; } /// <summary> /// csc.exe and vbc.exe entry point. /// </summary> public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default) { var saveUICulture = CultureInfo.CurrentUICulture; SarifErrorLogger? errorLogger = null; try { // Messages from exceptions can be used as arguments for errors and they are often localized. // Ensure they are localized to the right language. var culture = this.Culture; if (culture != null) { CultureInfo.CurrentUICulture = culture; } if (Arguments.ErrorLogOptions?.Path != null) { errorLogger = GetErrorLogger(consoleOutput, cancellationToken); if (errorLogger == null) { return Failed; } } return RunCore(consoleOutput, errorLogger, cancellationToken); } catch (OperationCanceledException) { var errorCode = MessageProvider.ERR_CompileCancelled; if (errorCode > 0) { var diag = new DiagnosticInfo(MessageProvider, errorCode); ReportDiagnostics(new[] { diag }, consoleOutput, errorLogger, compilation: null); } return Failed; } finally { CultureInfo.CurrentUICulture = saveUICulture; errorLogger?.Dispose(); } } /// <summary> /// Perform source generation, if the compiler supports it. /// </summary> /// <param name="input">The compilation before any source generation has occurred.</param> /// <param name="parseOptions">The <see cref="ParseOptions"/> to use when parsing any generated sources.</param> /// <param name="generators">The generators to run</param> /// <param name="analyzerConfigOptionsProvider">A provider that returns analyzer config options</param> /// <param name="additionalTexts">Any additional texts that should be passed to the generators when run.</param> /// <param name="generatorDiagnostics">Any diagnostics that were produced during generation</param> /// <returns>A compilation that represents the original compilation with any additional, generated texts added to it.</returns> private protected Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag generatorDiagnostics) { GeneratorDriver? driver = null; string cacheKey = string.Empty; bool disableCache = Arguments.ParseOptions.Features.ContainsKey("disable-generator-cache") || string.IsNullOrWhiteSpace(Arguments.OutputFileName); if (this.GeneratorDriverCache is object && !disableCache) { cacheKey = deriveCacheKey(); driver = this.GeneratorDriverCache.TryGetDriver(cacheKey); } driver ??= CreateGeneratorDriver(parseOptions, generators, analyzerConfigOptionsProvider, additionalTexts); driver = driver.RunGeneratorsAndUpdateCompilation(input, out var compilationOut, out var diagnostics); generatorDiagnostics.AddRange(diagnostics); if (!disableCache) { this.GeneratorDriverCache?.CacheGenerator(cacheKey, driver); } return compilationOut; string deriveCacheKey() { Debug.Assert(!string.IsNullOrWhiteSpace(Arguments.OutputFileName)); // CONSIDER: The only piece of the cache key that is required for correctness is the generators that were used. // We set up the graph statically based on the generators, so as long as the generator inputs haven't // changed we can technically run any project against another's cache and still get the correct results. // Obviously that would remove the point of the cache, so we also key off of the output file name // and output path so that collisions are unlikely and we'll usually get the correct cache for any // given compilation. PooledStringBuilder sb = PooledStringBuilder.GetInstance(); sb.Builder.Append(Arguments.GetOutputFilePath(Arguments.OutputFileName)); foreach (var generator in generators) { // append the generator FQN and the MVID of the assembly it came from, so any changes will invalidate the cache var type = generator.GetGeneratorType(); sb.Builder.Append(type.AssemblyQualifiedName); sb.Builder.Append(type.Assembly.ManifestModule.ModuleVersionId.ToString()); } return sb.ToStringAndFree(); } } private protected abstract GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts); private int RunCore(TextWriter consoleOutput, ErrorLogger? errorLogger, CancellationToken cancellationToken) { Debug.Assert(!Arguments.IsScriptRunner); cancellationToken.ThrowIfCancellationRequested(); if (Arguments.DisplayVersion) { PrintVersion(consoleOutput); return Succeeded; } if (Arguments.DisplayLangVersions) { PrintLangVersions(consoleOutput); return Succeeded; } if (Arguments.DisplayLogo) { PrintLogo(consoleOutput); } if (Arguments.DisplayHelp) { PrintHelp(consoleOutput); return Succeeded; } if (ReportDiagnostics(Arguments.Errors, consoleOutput, errorLogger, compilation: null)) { return Failed; } var touchedFilesLogger = (Arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; var diagnostics = DiagnosticBag.GetInstance(); AnalyzerConfigSet? analyzerConfigSet = null; ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions = default; AnalyzerConfigOptionsResult globalConfigOptions = default; if (Arguments.AnalyzerConfigPaths.Length > 0) { if (!TryGetAnalyzerConfigSet(Arguments.AnalyzerConfigPaths, diagnostics, out analyzerConfigSet)) { var hadErrors = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null); Debug.Assert(hadErrors); return Failed; } globalConfigOptions = analyzerConfigSet.GlobalConfigOptions; sourceFileAnalyzerConfigOptions = Arguments.SourceFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var sourceFileAnalyzerConfigOption in sourceFileAnalyzerConfigOptions) { diagnostics.AddRange(sourceFileAnalyzerConfigOption.Diagnostics); } } Compilation? compilation = CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, sourceFileAnalyzerConfigOptions, globalConfigOptions); if (compilation == null) { return Failed; } var diagnosticInfos = new List<DiagnosticInfo>(); ResolveAnalyzersFromArguments(diagnosticInfos, MessageProvider, Arguments.SkipAnalyzers, out var analyzers, out var generators); var additionalTextFiles = ResolveAdditionalFilesFromArguments(diagnosticInfos, MessageProvider, touchedFilesLogger); if (ReportDiagnostics(diagnosticInfos, consoleOutput, errorLogger, compilation)) { return Failed; } ImmutableArray<EmbeddedText?> embeddedTexts = AcquireEmbeddedTexts(compilation, diagnostics); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation)) { return Failed; } var additionalTexts = ImmutableArray<AdditionalText>.CastUp(additionalTextFiles); CompileAndEmit( touchedFilesLogger, ref compilation, analyzers, generators, additionalTexts, analyzerConfigSet, sourceFileAnalyzerConfigOptions, embeddedTexts, diagnostics, cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out var analyzerDriver); // At this point analyzers are already complete in which case this is a no-op. Or they are // still running because the compilation failed before all of the compilation events were // raised. In the latter case the driver, and all its associated state, will be waiting around // for events that are never coming. Cancel now and let the clean up process begin. if (analyzerCts != null) { analyzerCts.Cancel(); } var exitCode = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation) ? Failed : Succeeded; // The act of reporting errors can cause more errors to appear in // additional files due to forcing all additional files to fetch text foreach (var additionalFile in additionalTextFiles) { if (ReportDiagnostics(additionalFile.Diagnostics, consoleOutput, errorLogger, compilation)) { exitCode = Failed; } } diagnostics.Free(); if (reportAnalyzer) { Debug.Assert(analyzerDriver is object); ReportAnalyzerExecutionTime(consoleOutput, analyzerDriver, Culture, compilation.Options.ConcurrentBuild); } return exitCode; } private static CompilerAnalyzerConfigOptionsProvider UpdateAnalyzerConfigOptionsProvider( CompilerAnalyzerConfigOptionsProvider existing, IEnumerable<SyntaxTree> syntaxTrees, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<AdditionalText> additionalFiles = default, ImmutableArray<AnalyzerConfigOptionsResult> additionalFileOptions = default) { var builder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); int i = 0; foreach (var syntaxTree in syntaxTrees) { var options = sourceFileAnalyzerConfigOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(syntaxTree) == CompilerAnalyzerConfigOptions.Empty); builder.Add(syntaxTree, new CompilerAnalyzerConfigOptions(options)); } i++; } if (!additionalFiles.IsDefault) { for (i = 0; i < additionalFiles.Length; i++) { var options = additionalFileOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(additionalFiles[i]) == CompilerAnalyzerConfigOptions.Empty); builder.Add(additionalFiles[i], new CompilerAnalyzerConfigOptions(options)); } } } return existing.WithAdditionalTreeOptions(builder.ToImmutable()); } /// <summary> /// Perform all the work associated with actual compilation /// (parsing, binding, compile, emit), resulting in diagnostics /// and analyzer output. /// </summary> private void CompileAndEmit( TouchedFileLogger? touchedFilesLogger, ref Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<ISourceGenerator> generators, ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigSet? analyzerConfigSet, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<EmbeddedText?> embeddedTexts, DiagnosticBag diagnostics, CancellationToken cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out AnalyzerDriver? analyzerDriver) { analyzerCts = null; reportAnalyzer = false; analyzerDriver = null; // Print the diagnostics produced during the parsing stage and exit if there were any errors. compilation.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } DiagnosticBag? analyzerExceptionDiagnostics = null; if (!analyzers.IsEmpty || !generators.IsEmpty) { var analyzerConfigProvider = CompilerAnalyzerConfigOptionsProvider.Empty; if (Arguments.AnalyzerConfigPaths.Length > 0) { Debug.Assert(analyzerConfigSet is object); analyzerConfigProvider = analyzerConfigProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(analyzerConfigSet.GetOptionsForSourcePath(string.Empty).AnalyzerOptions)); // TODO(https://github.com/dotnet/roslyn/issues/31916): The compiler currently doesn't support // configuring diagnostic reporting on additional text files individually. ImmutableArray<AnalyzerConfigOptionsResult> additionalFileAnalyzerOptions = additionalTextFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var result in additionalFileAnalyzerOptions) { diagnostics.AddRange(result.Diagnostics); } analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, compilation.SyntaxTrees, sourceFileAnalyzerConfigOptions, additionalTextFiles, additionalFileAnalyzerOptions); } if (!generators.IsEmpty) { // At this point we have a compilation with nothing yet computed. // We pass it to the generators, which will realize any symbols they require. compilation = RunGenerators(compilation, Arguments.ParseOptions, generators, analyzerConfigProvider, additionalTextFiles, diagnostics); bool hasAnalyzerConfigs = !Arguments.AnalyzerConfigPaths.IsEmpty; bool hasGeneratedOutputPath = !string.IsNullOrWhiteSpace(Arguments.GeneratedFilesOutputDirectory); var generatedSyntaxTrees = compilation.SyntaxTrees.Skip(Arguments.SourceFiles.Length).ToList(); var analyzerOptionsBuilder = hasAnalyzerConfigs ? ArrayBuilder<AnalyzerConfigOptionsResult>.GetInstance(generatedSyntaxTrees.Count) : null; var embeddedTextBuilder = ArrayBuilder<EmbeddedText>.GetInstance(generatedSyntaxTrees.Count); try { foreach (var tree in generatedSyntaxTrees) { Debug.Assert(!string.IsNullOrWhiteSpace(tree.FilePath)); cancellationToken.ThrowIfCancellationRequested(); var sourceText = tree.GetText(cancellationToken); // embed the generated text and get analyzer options for it if needed embeddedTextBuilder.Add(EmbeddedText.FromSource(tree.FilePath, sourceText)); if (analyzerOptionsBuilder is object) { analyzerOptionsBuilder.Add(analyzerConfigSet!.GetOptionsForSourcePath(tree.FilePath)); } // write out the file if we have an output path if (hasGeneratedOutputPath) { var path = Path.Combine(Arguments.GeneratedFilesOutputDirectory!, tree.FilePath); if (Directory.Exists(Arguments.GeneratedFilesOutputDirectory)) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); } var fileStream = OpenFile(path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (fileStream is object) { Debug.Assert(tree.Encoding is object); using var disposer = new NoThrowStreamDisposer(fileStream, path, diagnostics, MessageProvider); using var writer = new StreamWriter(fileStream, tree.Encoding); sourceText.Write(writer, cancellationToken); touchedFilesLogger?.AddWritten(path); } } } embeddedTexts = embeddedTexts.AddRange(embeddedTextBuilder); if (analyzerOptionsBuilder is object) { analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, generatedSyntaxTrees, analyzerOptionsBuilder.ToImmutable()); } } finally { analyzerOptionsBuilder?.Free(); embeddedTextBuilder.Free(); } } AnalyzerOptions analyzerOptions = CreateAnalyzerOptions( additionalTextFiles, analyzerConfigProvider); if (!analyzers.IsEmpty) { analyzerCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); analyzerExceptionDiagnostics = new DiagnosticBag(); // PERF: Avoid executing analyzers that report only Hidden and/or Info diagnostics, which don't appear in the build output. // 1. Always filter out 'Hidden' analyzer diagnostics in build. // 2. Filter out 'Info' analyzer diagnostics if they are not required to be logged in errorlog. var severityFilter = SeverityFilter.Hidden; if (Arguments.ErrorLogPath == null) severityFilter |= SeverityFilter.Info; analyzerDriver = AnalyzerDriver.CreateAndAttachToCompilation( compilation, analyzers, analyzerOptions, new AnalyzerManager(analyzers), analyzerExceptionDiagnostics.Add, Arguments.ReportAnalyzer, severityFilter, out compilation, analyzerCts.Token); reportAnalyzer = Arguments.ReportAnalyzer && !analyzers.IsEmpty; } } compilation.GetDiagnostics(CompilationStage.Declare, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } cancellationToken.ThrowIfCancellationRequested(); // Given a compilation and a destination directory, determine three names: // 1) The name with which the assembly should be output. // 2) The path of the assembly/module file (default = destination directory + compilation output name). // 3) The path of the pdb file (default = assembly/module path with ".pdb" extension). string outputName = GetOutputFileName(compilation, cancellationToken)!; var finalPeFilePath = Arguments.GetOutputFilePath(outputName); var finalPdbFilePath = Arguments.GetPdbFilePath(outputName); var finalXmlFilePath = Arguments.DocumentationPath; NoThrowStreamDisposer? sourceLinkStreamDisposerOpt = null; try { // NOTE: Unlike the PDB path, the XML doc path is not embedded in the assembly, so we don't need to pass it to emit. var emitOptions = Arguments.EmitOptions. WithOutputNameOverride(outputName). WithPdbFilePath(PathUtilities.NormalizePathPrefix(finalPdbFilePath, Arguments.PathMap)); // TODO(https://github.com/dotnet/roslyn/issues/19592): // This feature flag is being maintained until our next major release to avoid unnecessary // compat breaks with customers. if (Arguments.ParseOptions.Features.ContainsKey("pdb-path-determinism") && !string.IsNullOrEmpty(emitOptions.PdbFilePath)) { emitOptions = emitOptions.WithPdbFilePath(Path.GetFileName(emitOptions.PdbFilePath)); } if (Arguments.SourceLink != null) { var sourceLinkStreamOpt = OpenFile( Arguments.SourceLink, diagnostics, FileMode.Open, FileAccess.Read, FileShare.Read); if (sourceLinkStreamOpt != null) { sourceLinkStreamDisposerOpt = new NoThrowStreamDisposer( sourceLinkStreamOpt, Arguments.SourceLink, diagnostics, MessageProvider); } } // Need to ensure the PDB file path validation is done on the original path as that is the // file we will write out to disk, there is no guarantee that the file paths emitted into // the PE / PDB are valid file paths because pathmap can be used to create deliberately // illegal names if (!PathUtilities.IsValidFilePath(finalPdbFilePath)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.FTL_InvalidInputFileName, Location.None, finalPdbFilePath)); } var moduleBeingBuilt = compilation.CheckOptionsAndCreateModuleBuilder( diagnostics, Arguments.ManifestResources, emitOptions, debugEntryPoint: null, sourceLinkStream: sourceLinkStreamDisposerOpt?.Stream, embeddedTexts: embeddedTexts, testData: null, cancellationToken: cancellationToken); if (moduleBeingBuilt != null) { bool success; try { success = compilation.CompileMethods( moduleBeingBuilt, Arguments.EmitPdb, emitOptions.EmitMetadataOnly, emitOptions.EmitTestCoverageData, diagnostics, filterOpt: null, cancellationToken: cancellationToken); // Prior to generating the xml documentation file, // we apply programmatic suppressions for compiler warnings from diagnostic suppressors. // If there are still any unsuppressed errors or warnings escalated to errors // then we bail out from generating the documentation file. // This maintains the compiler invariant that xml documentation file should not be // generated in presence of diagnostics that break the build. if (analyzerDriver != null && !diagnostics.IsEmptyWithoutResolution) { analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { // NOTE: as native compiler does, we generate the documentation file // NOTE: 'in place', replacing the contents of the file if it exists NoThrowStreamDisposer? xmlStreamDisposerOpt = null; if (finalXmlFilePath != null) { var xmlStreamOpt = OpenFile(finalXmlFilePath, diagnostics, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (xmlStreamOpt == null) { return; } try { xmlStreamOpt.SetLength(0); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, finalXmlFilePath, diagnostics); return; } xmlStreamDisposerOpt = new NoThrowStreamDisposer( xmlStreamOpt, finalXmlFilePath, diagnostics, MessageProvider); } using (xmlStreamDisposerOpt) { using (var win32ResourceStreamOpt = GetWin32Resources(FileSystem, MessageProvider, Arguments, compilation, diagnostics)) { if (HasUnsuppressableErrors(diagnostics)) { return; } success = compilation.GenerateResourcesAndDocumentationComments( moduleBeingBuilt, xmlStreamDisposerOpt?.Stream, win32ResourceStreamOpt, useRawWin32Resources: false, emitOptions.OutputNameOverride, diagnostics, cancellationToken); } } if (xmlStreamDisposerOpt?.HasFailedToDispose == true) { return; } // only report unused usings if we have success. if (success) { compilation.ReportUnusedImports(diagnostics, cancellationToken); } } compilation.CompleteTrees(null); if (analyzerDriver != null) { // GetDiagnosticsAsync is called after ReportUnusedImports // since that method calls EventQueue.TryComplete. Without // TryComplete, we may miss diagnostics. var hostDiagnostics = analyzerDriver.GetDiagnosticsAsync(compilation).Result; diagnostics.AddRange(hostDiagnostics); if (!diagnostics.IsEmptyWithoutResolution) { // Apply diagnostic suppressions for analyzer and/or compiler diagnostics from diagnostic suppressors. analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } } } finally { moduleBeingBuilt.CompilationFinished(); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { var peStreamProvider = new CompilerEmitStreamProvider(this, finalPeFilePath); var pdbStreamProviderOpt = Arguments.EmitPdbFile ? new CompilerEmitStreamProvider(this, finalPdbFilePath) : null; string? finalRefPeFilePath = Arguments.OutputRefFilePath; var refPeStreamProviderOpt = finalRefPeFilePath != null ? new CompilerEmitStreamProvider(this, finalRefPeFilePath) : null; RSAParameters? privateKeyOpt = null; if (compilation.Options.StrongNameProvider != null && compilation.SignUsingBuilder && !compilation.Options.PublicSign) { privateKeyOpt = compilation.StrongNameKeys.PrivateKey; } // If we serialize to a PE stream we need to record the fallback encoding if it was used // so the compilation can be recreated. emitOptions = emitOptions.WithFallbackSourceFileEncoding(GetFallbackEncoding()); success = compilation.SerializeToPeStream( moduleBeingBuilt, peStreamProvider, refPeStreamProviderOpt, pdbStreamProviderOpt, rebuildData: null, testSymWriterFactory: null, diagnostics: diagnostics, emitOptions: emitOptions, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken); peStreamProvider.Close(diagnostics); refPeStreamProviderOpt?.Close(diagnostics); pdbStreamProviderOpt?.Close(diagnostics); if (success && touchedFilesLogger != null) { if (pdbStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalPdbFilePath); } if (refPeStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalRefPeFilePath!); } touchedFilesLogger.AddWritten(finalPeFilePath); } } } if (HasUnsuppressableErrors(diagnostics)) { return; } } finally { sourceLinkStreamDisposerOpt?.Dispose(); } if (sourceLinkStreamDisposerOpt?.HasFailedToDispose == true) { return; } cancellationToken.ThrowIfCancellationRequested(); if (analyzerExceptionDiagnostics != null) { diagnostics.AddRange(analyzerExceptionDiagnostics); if (HasUnsuppressableErrors(analyzerExceptionDiagnostics)) { return; } } cancellationToken.ThrowIfCancellationRequested(); if (!WriteTouchedFiles(diagnostics, touchedFilesLogger, finalXmlFilePath)) { return; } } // virtual for testing protected virtual Diagnostics.AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) => new Diagnostics.AnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); private bool WriteTouchedFiles(DiagnosticBag diagnostics, TouchedFileLogger? touchedFilesLogger, string? finalXmlFilePath) { if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger != null); if (finalXmlFilePath != null) { touchedFilesLogger.AddWritten(finalXmlFilePath); } string readFilesPath = Arguments.TouchedFilesPath + ".read"; string writtenFilesPath = Arguments.TouchedFilesPath + ".write"; var readStream = OpenFile(readFilesPath, diagnostics, mode: FileMode.OpenOrCreate); var writtenStream = OpenFile(writtenFilesPath, diagnostics, mode: FileMode.OpenOrCreate); if (readStream == null || writtenStream == null) { return false; } string? filePath = null; try { filePath = readFilesPath; using (var writer = new StreamWriter(readStream)) { touchedFilesLogger.WriteReadPaths(writer); } filePath = writtenFilesPath; using (var writer = new StreamWriter(writtenStream)) { touchedFilesLogger.WriteWrittenPaths(writer); } } catch (Exception e) { Debug.Assert(filePath != null); MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return false; } } return true; } protected virtual ImmutableArray<AdditionalTextFile> ResolveAdditionalFilesFromArguments(List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, TouchedFileLogger? touchedFilesLogger) { var builder = ImmutableArray.CreateBuilder<AdditionalTextFile>(); foreach (var file in Arguments.AdditionalFiles) { builder.Add(new AdditionalTextFile(file, this)); } return builder.ToImmutableArray(); } private static void ReportAnalyzerExecutionTime(TextWriter consoleOutput, AnalyzerDriver analyzerDriver, CultureInfo culture, bool isConcurrentBuild) { Debug.Assert(analyzerDriver.AnalyzerExecutionTimes != null); if (analyzerDriver.AnalyzerExecutionTimes.IsEmpty) { return; } var totalAnalyzerExecutionTime = analyzerDriver.AnalyzerExecutionTimes.Sum(kvp => kvp.Value.TotalSeconds); Func<double, string> getFormattedTime = d => d.ToString("##0.000", culture); consoleOutput.WriteLine(); consoleOutput.WriteLine(string.Format(CodeAnalysisResources.AnalyzerTotalExecutionTime, getFormattedTime(totalAnalyzerExecutionTime))); if (isConcurrentBuild) { consoleOutput.WriteLine(CodeAnalysisResources.MultithreadedAnalyzerExecutionNote); } var analyzersByAssembly = analyzerDriver.AnalyzerExecutionTimes .GroupBy(kvp => kvp.Key.GetType().GetTypeInfo().Assembly) .OrderByDescending(kvp => kvp.Sum(entry => entry.Value.Ticks)); consoleOutput.WriteLine(); getFormattedTime = d => d < 0.001 ? string.Format(culture, "{0,8:<0.000}", 0.001) : string.Format(culture, "{0,8:##0.000}", d); Func<int, string> getFormattedPercentage = i => string.Format("{0,5}", i < 1 ? "<1" : i.ToString()); Func<string?, string> getFormattedAnalyzerName = s => " " + s; // Table header var analyzerTimeColumn = string.Format("{0,8}", CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader); var analyzerPercentageColumn = string.Format("{0,5}", "%"); var analyzerNameColumn = getFormattedAnalyzerName(CodeAnalysisResources.AnalyzerNameColumnHeader); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Table rows grouped by assembly. foreach (var analyzerGroup in analyzersByAssembly) { var executionTime = analyzerGroup.Sum(kvp => kvp.Value.TotalSeconds); var percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); analyzerNameColumn = getFormattedAnalyzerName(analyzerGroup.Key.FullName); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Rows for each diagnostic analyzer in the assembly. foreach (var kvp in analyzerGroup.OrderByDescending(kvp => kvp.Value)) { executionTime = kvp.Value.TotalSeconds; percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); var analyzerIds = string.Join(", ", kvp.Key.SupportedDiagnostics.Select(d => d.Id).Distinct().OrderBy(id => id)); analyzerNameColumn = getFormattedAnalyzerName($" {kvp.Key} ({analyzerIds})"); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); } consoleOutput.WriteLine(); } } /// <summary> /// Returns the name with which the assembly should be output /// </summary> protected abstract string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken); private Stream? OpenFile( string filePath, DiagnosticBag diagnostics, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None) { try { return FileSystem.OpenFile(filePath, mode, access, share); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return null; } } // internal for testing internal static Stream? GetWin32ResourcesInternal( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable<DiagnosticInfo> errors) { var diagnostics = DiagnosticBag.GetInstance(); var stream = GetWin32Resources(fileSystem, messageProvider, arguments, compilation, diagnostics); errors = diagnostics.ToReadOnlyAndFree().SelectAsArray(diag => new DiagnosticInfo(messageProvider, diag.IsWarningAsError, diag.Code, (object[])diag.Arguments)); return stream; } private static Stream? GetWin32Resources( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, DiagnosticBag diagnostics) { if (arguments.Win32ResourceFile != null) { return OpenStream(fileSystem, messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Resource, diagnostics); } using (Stream? manifestStream = OpenManifestStream(fileSystem, messageProvider, compilation.Options.OutputKind, arguments, diagnostics)) { using (Stream? iconStream = OpenStream(fileSystem, messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Icon, diagnostics)) { try { return compilation.CreateDefaultWin32Resources(true, arguments.NoWin32Manifest, manifestStream, iconStream); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_ErrorBuildingWin32Resource, Location.None, ex.Message)); } } } return null; } private static Stream? OpenManifestStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, OutputKind outputKind, CommandLineArguments arguments, DiagnosticBag diagnostics) { return outputKind.IsNetModule() ? null : OpenStream(fileSystem, messageProvider, arguments.Win32Manifest, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Manifest, diagnostics); } private static Stream? OpenStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, string? path, string? baseDirectory, int errorCode, DiagnosticBag diagnostics) { if (path == null) { return null; } string? fullPath = ResolveRelativePath(messageProvider, path, baseDirectory, diagnostics); if (fullPath == null) { return null; } try { return fileSystem.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(errorCode, Location.None, fullPath, ex.Message)); } return null; } private static string? ResolveRelativePath(CommonMessageProvider messageProvider, string path, string? baseDirectory, DiagnosticBag diagnostics) { string? fullPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (fullPath == null) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.FTL_InvalidInputFileName, Location.None, path ?? "")); } return fullPath; } internal static bool TryGetCompilerDiagnosticCode(string diagnosticId, string expectedPrefix, out uint code) { code = 0; return diagnosticId.StartsWith(expectedPrefix, StringComparison.Ordinal) && uint.TryParse(diagnosticId.Substring(expectedPrefix.Length), out code); } /// <summary> /// When overridden by a derived class, this property can override the current thread's /// CurrentUICulture property for diagnostic message resource lookups. /// </summary> protected virtual CultureInfo Culture { get { return Arguments.PreferredUILang ?? CultureInfo.CurrentUICulture; } } private static void EmitDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { var key = CreateDeterminismKey(args, rawArgs, baseDirectory, parser); var filePath = Path.Combine(args.OutputDirectory, args.OutputFileName + ".key"); using (var stream = File.Create(filePath)) { var bytes = Encoding.UTF8.GetBytes(key); stream.Write(bytes, 0, bytes.Length); } } /// <summary> /// The string returned from this function represents the inputs to the compiler which impact determinism. It is /// meant to be inline with the specification here: /// /// - https://github.com/dotnet/roslyn/blob/main/docs/compilers/Deterministic%20Inputs.md /// /// Issue #8193 tracks filling this out to the full specification. /// /// https://github.com/dotnet/roslyn/issues/8193 /// </summary> private static string CreateDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { List<Diagnostic> diagnostics = new List<Diagnostic>(); var flattenedArgs = ArrayBuilder<string>.GetInstance(); parser.FlattenArgs(rawArgs, diagnostics, flattenedArgs, null, baseDirectory); var builder = new StringBuilder(); var name = !string.IsNullOrEmpty(args.OutputFileName) ? Path.GetFileNameWithoutExtension(Path.GetFileName(args.OutputFileName)) : $"no-output-name-{Guid.NewGuid().ToString()}"; builder.AppendLine($"{name}"); builder.AppendLine($"Command Line:"); foreach (var current in flattenedArgs) { builder.AppendLine($"\t{current}"); } builder.AppendLine("Source Files:"); var hash = MD5.Create(); foreach (var sourceFile in args.SourceFiles) { var sourceFileName = Path.GetFileName(sourceFile.Path); string hashValue; try { var bytes = File.ReadAllBytes(sourceFile.Path); var hashBytes = hash.ComputeHash(bytes); var data = BitConverter.ToString(hashBytes); hashValue = data.Replace("-", ""); } catch (Exception ex) { hashValue = $"Could not compute {ex.Message}"; } builder.AppendLine($"\t{sourceFileName} - {hashValue}"); } flattenedArgs.Free(); return builder.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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal readonly struct BuildPaths { /// <summary> /// The path which contains the compiler binaries and response files. /// </summary> internal string ClientDirectory { get; } /// <summary> /// The path in which the compilation takes place. /// </summary> internal string WorkingDirectory { get; } /// <summary> /// The path which contains mscorlib. This can be null when specified by the user or running in a /// CoreClr environment. /// </summary> internal string? SdkDirectory { get; } /// <summary> /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>. The latter /// relies on global state individual compilations should ignore. /// </summary> internal string? TempDirectory { get; } internal BuildPaths(string clientDir, string workingDir, string? sdkDir, string? tempDir) { ClientDirectory = clientDir; WorkingDirectory = workingDir; SdkDirectory = sdkDir; TempDirectory = tempDir; } } /// <summary> /// Base class for csc.exe, csi.exe, vbc.exe and vbi.exe implementations. /// </summary> internal abstract partial class CommonCompiler { internal const int Failed = 1; internal const int Succeeded = 0; /// <summary> /// Fallback encoding that is lazily retrieved if needed. If <see cref="EncodedStringText.CreateFallbackEncoding"/> is /// evaluated and stored, the value is used if a PDB is created for this compilation. /// </summary> private readonly Lazy<Encoding> _fallbackEncoding = new Lazy<Encoding>(EncodedStringText.CreateFallbackEncoding); public CommonMessageProvider MessageProvider { get; } public CommandLineArguments Arguments { get; } public IAnalyzerAssemblyLoader AssemblyLoader { get; private set; } public GeneratorDriverCache? GeneratorDriverCache { get; } public abstract DiagnosticFormatter DiagnosticFormatter { get; } /// <summary> /// The set of source file paths that are in the set of embedded paths. /// This is used to prevent reading source files that are embedded twice. /// </summary> public IReadOnlySet<string> EmbeddedSourcePaths { get; } /// <summary> /// The <see cref="ICommonCompilerFileSystem"/> used to access the file system inside this instance. /// </summary> internal ICommonCompilerFileSystem FileSystem { get; set; } = StandardFileSystem.Instance; private readonly HashSet<Diagnostic> _reportedDiagnostics = new HashSet<Diagnostic>(); public abstract Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLoggerOpt, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions); public abstract void PrintLogo(TextWriter consoleOutput); public abstract void PrintHelp(TextWriter consoleOutput); public abstract void PrintLangVersions(TextWriter consoleOutput); /// <summary> /// Print compiler version /// </summary> /// <param name="consoleOutput"></param> public virtual void PrintVersion(TextWriter consoleOutput) { consoleOutput.WriteLine(GetCompilerVersion()); } protected abstract bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code); protected abstract void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators); public CommonCompiler(CommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader, GeneratorDriverCache? driverCache) { IEnumerable<string> allArgs = args; Debug.Assert(null == responseFile || PathUtilities.IsAbsolute(responseFile)); if (!SuppressDefaultResponseFile(args) && File.Exists(responseFile)) { allArgs = new[] { "@" + responseFile }.Concat(allArgs); } this.Arguments = parser.Parse(allArgs, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, additionalReferenceDirectories); this.MessageProvider = parser.MessageProvider; this.AssemblyLoader = assemblyLoader; this.GeneratorDriverCache = driverCache; this.EmbeddedSourcePaths = GetEmbeddedSourcePaths(Arguments); if (Arguments.ParseOptions.Features.ContainsKey("debug-determinism")) { EmitDeterminismKey(Arguments, args, buildPaths.WorkingDirectory, parser); } } internal abstract bool SuppressDefaultResponseFile(IEnumerable<string> args); /// <summary> /// The type of the compiler class for version information in /help and /version. /// We don't simply use this.GetType() because that would break mock subclasses. /// </summary> internal abstract Type Type { get; } /// <summary> /// The version of this compiler with commit hash, used in logo and /version output. /// </summary> internal string GetCompilerVersion() { return GetProductVersion(Type); } internal static string GetProductVersion(Type type) { string? assemblyVersion = GetInformationalVersionWithoutHash(type); string? hash = GetShortCommitHash(type); return $"{assemblyVersion} ({hash})"; } [return: NotNullIfNotNull("hash")] internal static string? ExtractShortCommitHash(string? hash) { // leave "<developer build>" alone, but truncate SHA to 8 characters if (hash != null && hash.Length >= 8 && hash[0] != '<') { return hash.Substring(0, 8); } return hash; } private static string? GetInformationalVersionWithoutHash(Type type) { // The attribute stores a SemVer2-formatted string: `A.B.C(-...)?(+...)?` // We remove the section after the + (if any is present) return type.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0]; } private static string? GetShortCommitHash(Type type) { var hash = type.Assembly.GetCustomAttribute<CommitHashAttribute>()?.Hash; return ExtractShortCommitHash(hash); } /// <summary> /// Tool name used, along with assembly version, for error logging. /// </summary> internal abstract string GetToolName(); /// <summary> /// Tool version identifier used for error logging. /// </summary> internal Version? GetAssemblyVersion() { return Type.GetTypeInfo().Assembly.GetName().Version; } internal string GetCultureName() { return Culture.Name; } internal virtual Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return (path, properties) => { var peStream = FileSystem.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read); return MetadataReference.CreateFromFile(peStream, path, properties); }; } internal virtual MetadataReferenceResolver GetCommandLineMetadataReferenceResolver(TouchedFileLogger? loggerOpt) { var pathResolver = new CompilerRelativePathResolver(FileSystem, Arguments.ReferencePaths, Arguments.BaseDirectory!); return new LoggingMetadataFileReferenceResolver(pathResolver, GetMetadataProvider(), loggerOpt); } /// <summary> /// Resolves metadata references stored in command line arguments and reports errors for those that can't be resolved. /// </summary> internal List<MetadataReference> ResolveMetadataReferences( List<DiagnosticInfo> diagnostics, TouchedFileLogger? touchedFiles, out MetadataReferenceResolver referenceDirectiveResolver) { var commandLineReferenceResolver = GetCommandLineMetadataReferenceResolver(touchedFiles); List<MetadataReference> resolved = new List<MetadataReference>(); Arguments.ResolveMetadataReferences(commandLineReferenceResolver, diagnostics, this.MessageProvider, resolved); if (Arguments.IsScriptRunner) { referenceDirectiveResolver = commandLineReferenceResolver; } else { // when compiling into an assembly (csc/vbc) we only allow #r that match references given on command line: referenceDirectiveResolver = new ExistingReferencesResolver(commandLineReferenceResolver, resolved.ToImmutableArray()); } return resolved; } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics) { return TryReadFileContent(file, diagnostics, out _); } /// <summary> /// Reads content of a source file. /// </summary> /// <param name="file">Source file information.</param> /// <param name="diagnostics">Storage for diagnostics.</param> /// <param name="normalizedFilePath">If given <paramref name="file"/> opens successfully, set to normalized absolute path of the file, null otherwise.</param> /// <returns>File content or null on failure.</returns> internal SourceText? TryReadFileContent(CommandLineSourceFile file, IList<DiagnosticInfo> diagnostics, out string? normalizedFilePath) { var filePath = file.Path; try { if (file.IsInputRedirected) { using var data = Console.OpenStandardInput(); normalizedFilePath = filePath; return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } else { using var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedFilePath); return EncodedStringText.Create(data, _fallbackEncoding, Arguments.Encoding, Arguments.ChecksumAlgorithm, canBeEmbedded: EmbeddedSourcePaths.Contains(file.Path)); } } catch (Exception e) { diagnostics.Add(ToFileReadDiagnostics(this.MessageProvider, e, filePath)); normalizedFilePath = null; return null; } } /// <summary> /// Read all analyzer config files from the given paths. /// </summary> internal bool TryGetAnalyzerConfigSet( ImmutableArray<string> analyzerConfigPaths, DiagnosticBag diagnostics, [NotNullWhen(true)] out AnalyzerConfigSet? analyzerConfigSet) { var configs = ArrayBuilder<AnalyzerConfig>.GetInstance(analyzerConfigPaths.Length); var processedDirs = PooledHashSet<string>.GetInstance(); foreach (var configPath in analyzerConfigPaths) { // The editorconfig spec requires all paths use '/' as the directory separator. // Since no known system allows directory separators as part of the file name, // we can replace every instance of the directory separator with a '/' string? fileContent = TryReadFileContent(configPath, diagnostics, out string? normalizedPath); if (fileContent is null) { // Error reading a file. Bail out and report error. break; } Debug.Assert(normalizedPath is object); var directory = Path.GetDirectoryName(normalizedPath) ?? normalizedPath; var editorConfig = AnalyzerConfig.Parse(fileContent, normalizedPath); if (!editorConfig.IsGlobal) { if (processedDirs.Contains(directory)) { diagnostics.Add(Diagnostic.Create( MessageProvider, MessageProvider.ERR_MultipleAnalyzerConfigsInSameDir, directory)); break; } processedDirs.Add(directory); } configs.Add(editorConfig); } processedDirs.Free(); if (diagnostics.HasAnyErrors()) { configs.Free(); analyzerConfigSet = null; return false; } analyzerConfigSet = AnalyzerConfigSet.Create(configs, out var setDiagnostics); diagnostics.AddRange(setDiagnostics); return true; } /// <summary> /// Returns the fallback encoding for parsing source files, if used, or null /// if not used /// </summary> internal Encoding? GetFallbackEncoding() { if (_fallbackEncoding.IsValueCreated) { return _fallbackEncoding.Value; } return null; } /// <summary> /// Read a UTF-8 encoded file and return the text as a string. /// </summary> private string? TryReadFileContent(string filePath, DiagnosticBag diagnostics, out string? normalizedPath) { try { var data = OpenFileForReadWithSmallBufferOptimization(filePath, out normalizedPath); using (var reader = new StreamReader(data, Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (Exception e) { diagnostics.Add(Diagnostic.Create(ToFileReadDiagnostics(MessageProvider, e, filePath))); normalizedPath = null; return null; } } private Stream OpenFileForReadWithSmallBufferOptimization(string filePath, out string normalizedFilePath) // PERF: Using a very small buffer size for the FileStream opens up an optimization within EncodedStringText/EmbeddedText where // we read the entire FileStream into a byte array in one shot. For files that are actually smaller than the buffer // size, FileStream.Read still allocates the internal buffer. => FileSystem.OpenFileEx( filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1, options: FileOptions.None, out normalizedFilePath); internal EmbeddedText? TryReadEmbeddedFileContent(string filePath, DiagnosticBag diagnostics) { try { using (var stream = OpenFileForReadWithSmallBufferOptimization(filePath, out _)) { const int LargeObjectHeapLimit = 80 * 1024; if (stream.Length < LargeObjectHeapLimit) { ArraySegment<byte> bytes; if (EncodedStringText.TryGetBytesFromStream(stream, out bytes)) { return EmbeddedText.FromBytes(filePath, bytes, Arguments.ChecksumAlgorithm); } } return EmbeddedText.FromStream(filePath, stream, Arguments.ChecksumAlgorithm); } } catch (Exception e) { diagnostics.Add(MessageProvider.CreateDiagnostic(ToFileReadDiagnostics(this.MessageProvider, e, filePath))); return null; } } private ImmutableArray<EmbeddedText?> AcquireEmbeddedTexts(Compilation compilation, DiagnosticBag diagnostics) { Debug.Assert(compilation.Options.SourceReferenceResolver is object); if (Arguments.EmbeddedFiles.IsEmpty) { return ImmutableArray<EmbeddedText?>.Empty; } var embeddedTreeMap = new Dictionary<string, SyntaxTree>(Arguments.EmbeddedFiles.Length); var embeddedFileOrderedSet = new OrderedSet<string>(Arguments.EmbeddedFiles.Select(e => e.Path)); foreach (var tree in compilation.SyntaxTrees) { // Skip trees that will not have their text embedded. if (!EmbeddedSourcePaths.Contains(tree.FilePath)) { continue; } // Skip trees with duplicated paths. (VB allows this and "first tree wins" is same as PDB emit policy.) if (embeddedTreeMap.ContainsKey(tree.FilePath)) { continue; } // map embedded file path to corresponding source tree embeddedTreeMap.Add(tree.FilePath, tree); // also embed the text of any #line directive targets of embedded tree ResolveEmbeddedFilesFromExternalSourceDirectives(tree, compilation.Options.SourceReferenceResolver, embeddedFileOrderedSet, diagnostics); } var embeddedTextBuilder = ImmutableArray.CreateBuilder<EmbeddedText?>(embeddedFileOrderedSet.Count); foreach (var path in embeddedFileOrderedSet) { SyntaxTree? tree; EmbeddedText? text; if (embeddedTreeMap.TryGetValue(path, out tree)) { text = EmbeddedText.FromSource(path, tree.GetText()); Debug.Assert(text != null); } else { text = TryReadEmbeddedFileContent(path, diagnostics); Debug.Assert(text != null || diagnostics.HasAnyErrors()); } // We can safely add nulls because result will be ignored if any error is produced. // This allows the MoveToImmutable to work below in all cases. embeddedTextBuilder.Add(text); } return embeddedTextBuilder.MoveToImmutable(); } protected abstract void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics); private static IReadOnlySet<string> GetEmbeddedSourcePaths(CommandLineArguments arguments) { if (arguments.EmbeddedFiles.IsEmpty) { return SpecializedCollections.EmptyReadOnlySet<string>(); } // Note that we require an exact match between source and embedded file paths (case-sensitive // and without normalization). If two files are the same but spelled differently, they will // be handled as separate files, meaning the embedding pass will read the content a second // time. This can also lead to more than one document entry in the PDB for the same document // if the PDB document de-duping policy in emit (normalize + case-sensitive in C#, // normalize + case-insensitive in VB) is not enough to converge them. var set = new HashSet<string>(arguments.EmbeddedFiles.Select(f => f.Path)); set.IntersectWith(arguments.SourceFiles.Select(f => f.Path)); return SpecializedCollections.StronglyTypedReadOnlySet(set); } internal static DiagnosticInfo ToFileReadDiagnostics(CommonMessageProvider messageProvider, Exception e, string filePath) { DiagnosticInfo diagnosticInfo; if (e is FileNotFoundException || e is DirectoryNotFoundException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_FileNotFound, filePath); } else if (e is InvalidDataException) { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_BinaryFile, filePath); } else { diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_NoSourceFile, filePath, e.Message); } return diagnosticInfo; } /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<Diagnostic> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) { bool hasErrors = false; foreach (var diag in diagnostics) { reportDiagnostic(diag, compilation == null ? null : diag.GetSuppressionInfo(compilation)); } return hasErrors; // Local functions void reportDiagnostic(Diagnostic diag, SuppressionInfo? suppressionInfo) { if (_reportedDiagnostics.Contains(diag)) { // TODO: This invariant fails (at least) in the case where we see a member declaration "x = 1;". // First we attempt to parse a member declaration starting at "x". When we see the "=", we // create an IncompleteMemberSyntax with return type "x" and an error at the location of the "x". // Then we parse a member declaration starting at "=". This is an invalid member declaration start // so we attach an error to the "=" and attach it (plus following tokens) to the IncompleteMemberSyntax // we previously created. //this assert isn't valid if we change the design to not bail out after each phase. //System.Diagnostics.Debug.Assert(diag.Severity != DiagnosticSeverity.Error); return; } else if (diag.Severity == DiagnosticSeverity.Hidden) { // Not reported from the command-line compiler. return; } // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics should not be reported on the console output. errorLoggerOpt?.LogDiagnostic(diag, suppressionInfo); // If the diagnostic was suppressed by one or more DiagnosticSuppressor(s), then we report info diagnostics for each suppression // so that the suppression information is available in the binary logs and verbose build logs. if (diag.ProgrammaticSuppressionInfo != null) { foreach (var (id, justification) in diag.ProgrammaticSuppressionInfo.Suppressions) { var suppressionDiag = new SuppressionDiagnostic(diag, id, justification); if (_reportedDiagnostics.Add(suppressionDiag)) { PrintError(suppressionDiag, consoleOutput); } } _reportedDiagnostics.Add(diag); return; } if (diag.IsSuppressed) { return; } // Diagnostics that aren't suppressed will be reported to the console output and, if they are errors, // they should fail the run if (diag.Severity == DiagnosticSeverity.Error) { hasErrors = true; } PrintError(diag, consoleOutput); _reportedDiagnostics.Add(diag); } } /// <summary>Returns true if there were any errors, false otherwise.</summary> private bool ReportDiagnostics(DiagnosticBag diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.ToReadOnly(), consoleOutput, errorLoggerOpt, compilation); /// <summary>Returns true if there were any errors, false otherwise.</summary> internal bool ReportDiagnostics(IEnumerable<DiagnosticInfo> diagnostics, TextWriter consoleOutput, ErrorLogger? errorLoggerOpt, Compilation? compilation) => ReportDiagnostics(diagnostics.Select(info => Diagnostic.Create(info)), consoleOutput, errorLoggerOpt, compilation); /// <summary> /// Returns true if there are any error diagnostics in the bag which cannot be suppressed and /// are guaranteed to break the build. /// Only diagnostics which have default severity error and are tagged as NotConfigurable fall in this bucket. /// This includes all compiler error diagnostics and specific analyzer error diagnostics that are marked as not configurable by the analyzer author. /// </summary> internal static bool HasUnsuppressableErrors(DiagnosticBag diagnostics) { foreach (var diag in diagnostics.AsEnumerable()) { if (diag.IsUnsuppressableError()) { return true; } } return false; } /// <summary> /// Returns true if the bag has any diagnostics with effective Severity=Error. Also returns true for warnings or informationals /// or warnings promoted to error via /warnaserror which are not suppressed. /// </summary> internal static bool HasUnsuppressedErrors(DiagnosticBag diagnostics) { foreach (Diagnostic diagnostic in diagnostics.AsEnumerable()) { if (diagnostic.IsUnsuppressedError) { return true; } } return false; } protected virtual void PrintError(Diagnostic diagnostic, TextWriter consoleOutput) { consoleOutput.WriteLine(DiagnosticFormatter.Format(diagnostic, Culture)); } public SarifErrorLogger? GetErrorLogger(TextWriter consoleOutput, CancellationToken cancellationToken) { Debug.Assert(Arguments.ErrorLogOptions?.Path != null); var diagnostics = DiagnosticBag.GetInstance(); var errorLog = OpenFile(Arguments.ErrorLogOptions.Path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); SarifErrorLogger? logger; if (errorLog == null) { Debug.Assert(diagnostics.HasAnyErrors()); logger = null; } else { string toolName = GetToolName(); string compilerVersion = GetCompilerVersion(); Version assemblyVersion = GetAssemblyVersion() ?? new Version(); if (Arguments.ErrorLogOptions.SarifVersion == SarifVersion.Sarif1) { logger = new SarifV1ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } else { logger = new SarifV2ErrorLogger(errorLog, toolName, compilerVersion, assemblyVersion, Culture); } } ReportDiagnostics(diagnostics.ToReadOnlyAndFree(), consoleOutput, errorLoggerOpt: logger, compilation: null); return logger; } /// <summary> /// csc.exe and vbc.exe entry point. /// </summary> public virtual int Run(TextWriter consoleOutput, CancellationToken cancellationToken = default) { var saveUICulture = CultureInfo.CurrentUICulture; SarifErrorLogger? errorLogger = null; try { // Messages from exceptions can be used as arguments for errors and they are often localized. // Ensure they are localized to the right language. var culture = this.Culture; if (culture != null) { CultureInfo.CurrentUICulture = culture; } if (Arguments.ErrorLogOptions?.Path != null) { errorLogger = GetErrorLogger(consoleOutput, cancellationToken); if (errorLogger == null) { return Failed; } } return RunCore(consoleOutput, errorLogger, cancellationToken); } catch (OperationCanceledException) { var errorCode = MessageProvider.ERR_CompileCancelled; if (errorCode > 0) { var diag = new DiagnosticInfo(MessageProvider, errorCode); ReportDiagnostics(new[] { diag }, consoleOutput, errorLogger, compilation: null); } return Failed; } finally { CultureInfo.CurrentUICulture = saveUICulture; errorLogger?.Dispose(); } } /// <summary> /// Perform source generation, if the compiler supports it. /// </summary> /// <param name="input">The compilation before any source generation has occurred.</param> /// <param name="parseOptions">The <see cref="ParseOptions"/> to use when parsing any generated sources.</param> /// <param name="generators">The generators to run</param> /// <param name="analyzerConfigOptionsProvider">A provider that returns analyzer config options</param> /// <param name="additionalTexts">Any additional texts that should be passed to the generators when run.</param> /// <param name="generatorDiagnostics">Any diagnostics that were produced during generation</param> /// <returns>A compilation that represents the original compilation with any additional, generated texts added to it.</returns> private protected Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag generatorDiagnostics) { GeneratorDriver? driver = null; string cacheKey = string.Empty; bool disableCache = Arguments.ParseOptions.Features.ContainsKey("disable-generator-cache") || string.IsNullOrWhiteSpace(Arguments.OutputFileName); if (this.GeneratorDriverCache is object && !disableCache) { cacheKey = deriveCacheKey(); driver = this.GeneratorDriverCache.TryGetDriver(cacheKey); } driver ??= CreateGeneratorDriver(parseOptions, generators, analyzerConfigOptionsProvider, additionalTexts); driver = driver.RunGeneratorsAndUpdateCompilation(input, out var compilationOut, out var diagnostics); generatorDiagnostics.AddRange(diagnostics); if (!disableCache) { this.GeneratorDriverCache?.CacheGenerator(cacheKey, driver); } return compilationOut; string deriveCacheKey() { Debug.Assert(!string.IsNullOrWhiteSpace(Arguments.OutputFileName)); // CONSIDER: The only piece of the cache key that is required for correctness is the generators that were used. // We set up the graph statically based on the generators, so as long as the generator inputs haven't // changed we can technically run any project against another's cache and still get the correct results. // Obviously that would remove the point of the cache, so we also key off of the output file name // and output path so that collisions are unlikely and we'll usually get the correct cache for any // given compilation. PooledStringBuilder sb = PooledStringBuilder.GetInstance(); sb.Builder.Append(Arguments.GetOutputFilePath(Arguments.OutputFileName)); foreach (var generator in generators) { // append the generator FQN and the MVID of the assembly it came from, so any changes will invalidate the cache var type = generator.GetGeneratorType(); sb.Builder.Append(type.AssemblyQualifiedName); sb.Builder.Append(type.Assembly.ManifestModule.ModuleVersionId.ToString()); } return sb.ToStringAndFree(); } } private protected abstract GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider, ImmutableArray<AdditionalText> additionalTexts); private int RunCore(TextWriter consoleOutput, ErrorLogger? errorLogger, CancellationToken cancellationToken) { Debug.Assert(!Arguments.IsScriptRunner); cancellationToken.ThrowIfCancellationRequested(); if (Arguments.DisplayVersion) { PrintVersion(consoleOutput); return Succeeded; } if (Arguments.DisplayLangVersions) { PrintLangVersions(consoleOutput); return Succeeded; } if (Arguments.DisplayLogo) { PrintLogo(consoleOutput); } if (Arguments.DisplayHelp) { PrintHelp(consoleOutput); return Succeeded; } if (ReportDiagnostics(Arguments.Errors, consoleOutput, errorLogger, compilation: null)) { return Failed; } var touchedFilesLogger = (Arguments.TouchedFilesPath != null) ? new TouchedFileLogger() : null; var diagnostics = DiagnosticBag.GetInstance(); AnalyzerConfigSet? analyzerConfigSet = null; ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions = default; AnalyzerConfigOptionsResult globalConfigOptions = default; if (Arguments.AnalyzerConfigPaths.Length > 0) { if (!TryGetAnalyzerConfigSet(Arguments.AnalyzerConfigPaths, diagnostics, out analyzerConfigSet)) { var hadErrors = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null); Debug.Assert(hadErrors); return Failed; } globalConfigOptions = analyzerConfigSet.GlobalConfigOptions; sourceFileAnalyzerConfigOptions = Arguments.SourceFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var sourceFileAnalyzerConfigOption in sourceFileAnalyzerConfigOptions) { diagnostics.AddRange(sourceFileAnalyzerConfigOption.Diagnostics); } } Compilation? compilation = CreateCompilation(consoleOutput, touchedFilesLogger, errorLogger, sourceFileAnalyzerConfigOptions, globalConfigOptions); if (compilation == null) { return Failed; } var diagnosticInfos = new List<DiagnosticInfo>(); ResolveAnalyzersFromArguments(diagnosticInfos, MessageProvider, Arguments.SkipAnalyzers, out var analyzers, out var generators); var additionalTextFiles = ResolveAdditionalFilesFromArguments(diagnosticInfos, MessageProvider, touchedFilesLogger); if (ReportDiagnostics(diagnosticInfos, consoleOutput, errorLogger, compilation)) { return Failed; } ImmutableArray<EmbeddedText?> embeddedTexts = AcquireEmbeddedTexts(compilation, diagnostics); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation)) { return Failed; } var additionalTexts = ImmutableArray<AdditionalText>.CastUp(additionalTextFiles); CompileAndEmit( touchedFilesLogger, ref compilation, analyzers, generators, additionalTexts, analyzerConfigSet, sourceFileAnalyzerConfigOptions, embeddedTexts, diagnostics, cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out var analyzerDriver); // At this point analyzers are already complete in which case this is a no-op. Or they are // still running because the compilation failed before all of the compilation events were // raised. In the latter case the driver, and all its associated state, will be waiting around // for events that are never coming. Cancel now and let the clean up process begin. if (analyzerCts != null) { analyzerCts.Cancel(); } var exitCode = ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation) ? Failed : Succeeded; // The act of reporting errors can cause more errors to appear in // additional files due to forcing all additional files to fetch text foreach (var additionalFile in additionalTextFiles) { if (ReportDiagnostics(additionalFile.Diagnostics, consoleOutput, errorLogger, compilation)) { exitCode = Failed; } } diagnostics.Free(); if (reportAnalyzer) { Debug.Assert(analyzerDriver is object); ReportAnalyzerExecutionTime(consoleOutput, analyzerDriver, Culture, compilation.Options.ConcurrentBuild); } return exitCode; } private static CompilerAnalyzerConfigOptionsProvider UpdateAnalyzerConfigOptionsProvider( CompilerAnalyzerConfigOptionsProvider existing, IEnumerable<SyntaxTree> syntaxTrees, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<AdditionalText> additionalFiles = default, ImmutableArray<AnalyzerConfigOptionsResult> additionalFileOptions = default) { var builder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); int i = 0; foreach (var syntaxTree in syntaxTrees) { var options = sourceFileAnalyzerConfigOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(syntaxTree) == CompilerAnalyzerConfigOptions.Empty); builder.Add(syntaxTree, new CompilerAnalyzerConfigOptions(options)); } i++; } if (!additionalFiles.IsDefault) { for (i = 0; i < additionalFiles.Length; i++) { var options = additionalFileOptions[i].AnalyzerOptions; // Optimization: don't create a bunch of entries pointing to a no-op if (options.Count > 0) { Debug.Assert(existing.GetOptions(additionalFiles[i]) == CompilerAnalyzerConfigOptions.Empty); builder.Add(additionalFiles[i], new CompilerAnalyzerConfigOptions(options)); } } } return existing.WithAdditionalTreeOptions(builder.ToImmutable()); } /// <summary> /// Perform all the work associated with actual compilation /// (parsing, binding, compile, emit), resulting in diagnostics /// and analyzer output. /// </summary> private void CompileAndEmit( TouchedFileLogger? touchedFilesLogger, ref Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<ISourceGenerator> generators, ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigSet? analyzerConfigSet, ImmutableArray<AnalyzerConfigOptionsResult> sourceFileAnalyzerConfigOptions, ImmutableArray<EmbeddedText?> embeddedTexts, DiagnosticBag diagnostics, CancellationToken cancellationToken, out CancellationTokenSource? analyzerCts, out bool reportAnalyzer, out AnalyzerDriver? analyzerDriver) { analyzerCts = null; reportAnalyzer = false; analyzerDriver = null; // Print the diagnostics produced during the parsing stage and exit if there were any errors. compilation.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } DiagnosticBag? analyzerExceptionDiagnostics = null; if (!analyzers.IsEmpty || !generators.IsEmpty) { var analyzerConfigProvider = CompilerAnalyzerConfigOptionsProvider.Empty; if (Arguments.AnalyzerConfigPaths.Length > 0) { Debug.Assert(analyzerConfigSet is object); analyzerConfigProvider = analyzerConfigProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(analyzerConfigSet.GetOptionsForSourcePath(string.Empty).AnalyzerOptions)); // TODO(https://github.com/dotnet/roslyn/issues/31916): The compiler currently doesn't support // configuring diagnostic reporting on additional text files individually. ImmutableArray<AnalyzerConfigOptionsResult> additionalFileAnalyzerOptions = additionalTextFiles.SelectAsArray(f => analyzerConfigSet.GetOptionsForSourcePath(f.Path)); foreach (var result in additionalFileAnalyzerOptions) { diagnostics.AddRange(result.Diagnostics); } analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, compilation.SyntaxTrees, sourceFileAnalyzerConfigOptions, additionalTextFiles, additionalFileAnalyzerOptions); } if (!generators.IsEmpty) { // At this point we have a compilation with nothing yet computed. // We pass it to the generators, which will realize any symbols they require. compilation = RunGenerators(compilation, Arguments.ParseOptions, generators, analyzerConfigProvider, additionalTextFiles, diagnostics); bool hasAnalyzerConfigs = !Arguments.AnalyzerConfigPaths.IsEmpty; bool hasGeneratedOutputPath = !string.IsNullOrWhiteSpace(Arguments.GeneratedFilesOutputDirectory); var generatedSyntaxTrees = compilation.SyntaxTrees.Skip(Arguments.SourceFiles.Length).ToList(); var analyzerOptionsBuilder = hasAnalyzerConfigs ? ArrayBuilder<AnalyzerConfigOptionsResult>.GetInstance(generatedSyntaxTrees.Count) : null; var embeddedTextBuilder = ArrayBuilder<EmbeddedText>.GetInstance(generatedSyntaxTrees.Count); try { foreach (var tree in generatedSyntaxTrees) { Debug.Assert(!string.IsNullOrWhiteSpace(tree.FilePath)); cancellationToken.ThrowIfCancellationRequested(); var sourceText = tree.GetText(cancellationToken); // embed the generated text and get analyzer options for it if needed embeddedTextBuilder.Add(EmbeddedText.FromSource(tree.FilePath, sourceText)); if (analyzerOptionsBuilder is object) { analyzerOptionsBuilder.Add(analyzerConfigSet!.GetOptionsForSourcePath(tree.FilePath)); } // write out the file if we have an output path if (hasGeneratedOutputPath) { var path = Path.Combine(Arguments.GeneratedFilesOutputDirectory!, tree.FilePath); if (Directory.Exists(Arguments.GeneratedFilesOutputDirectory)) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); } var fileStream = OpenFile(path, diagnostics, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (fileStream is object) { Debug.Assert(tree.Encoding is object); using var disposer = new NoThrowStreamDisposer(fileStream, path, diagnostics, MessageProvider); using var writer = new StreamWriter(fileStream, tree.Encoding); sourceText.Write(writer, cancellationToken); touchedFilesLogger?.AddWritten(path); } } } embeddedTexts = embeddedTexts.AddRange(embeddedTextBuilder); if (analyzerOptionsBuilder is object) { analyzerConfigProvider = UpdateAnalyzerConfigOptionsProvider( analyzerConfigProvider, generatedSyntaxTrees, analyzerOptionsBuilder.ToImmutable()); } } finally { analyzerOptionsBuilder?.Free(); embeddedTextBuilder.Free(); } } AnalyzerOptions analyzerOptions = CreateAnalyzerOptions( additionalTextFiles, analyzerConfigProvider); if (!analyzers.IsEmpty) { analyzerCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); analyzerExceptionDiagnostics = new DiagnosticBag(); // PERF: Avoid executing analyzers that report only Hidden and/or Info diagnostics, which don't appear in the build output. // 1. Always filter out 'Hidden' analyzer diagnostics in build. // 2. Filter out 'Info' analyzer diagnostics if they are not required to be logged in errorlog. var severityFilter = SeverityFilter.Hidden; if (Arguments.ErrorLogPath == null) severityFilter |= SeverityFilter.Info; analyzerDriver = AnalyzerDriver.CreateAndAttachToCompilation( compilation, analyzers, analyzerOptions, new AnalyzerManager(analyzers), analyzerExceptionDiagnostics.Add, Arguments.ReportAnalyzer, severityFilter, out compilation, analyzerCts.Token); reportAnalyzer = Arguments.ReportAnalyzer && !analyzers.IsEmpty; } } compilation.GetDiagnostics(CompilationStage.Declare, includeEarlierStages: false, diagnostics, cancellationToken); if (HasUnsuppressableErrors(diagnostics)) { return; } cancellationToken.ThrowIfCancellationRequested(); // Given a compilation and a destination directory, determine three names: // 1) The name with which the assembly should be output. // 2) The path of the assembly/module file (default = destination directory + compilation output name). // 3) The path of the pdb file (default = assembly/module path with ".pdb" extension). string outputName = GetOutputFileName(compilation, cancellationToken)!; var finalPeFilePath = Arguments.GetOutputFilePath(outputName); var finalPdbFilePath = Arguments.GetPdbFilePath(outputName); var finalXmlFilePath = Arguments.DocumentationPath; NoThrowStreamDisposer? sourceLinkStreamDisposerOpt = null; try { // NOTE: Unlike the PDB path, the XML doc path is not embedded in the assembly, so we don't need to pass it to emit. var emitOptions = Arguments.EmitOptions. WithOutputNameOverride(outputName). WithPdbFilePath(PathUtilities.NormalizePathPrefix(finalPdbFilePath, Arguments.PathMap)); // TODO(https://github.com/dotnet/roslyn/issues/19592): // This feature flag is being maintained until our next major release to avoid unnecessary // compat breaks with customers. if (Arguments.ParseOptions.Features.ContainsKey("pdb-path-determinism") && !string.IsNullOrEmpty(emitOptions.PdbFilePath)) { emitOptions = emitOptions.WithPdbFilePath(Path.GetFileName(emitOptions.PdbFilePath)); } if (Arguments.SourceLink != null) { var sourceLinkStreamOpt = OpenFile( Arguments.SourceLink, diagnostics, FileMode.Open, FileAccess.Read, FileShare.Read); if (sourceLinkStreamOpt != null) { sourceLinkStreamDisposerOpt = new NoThrowStreamDisposer( sourceLinkStreamOpt, Arguments.SourceLink, diagnostics, MessageProvider); } } // Need to ensure the PDB file path validation is done on the original path as that is the // file we will write out to disk, there is no guarantee that the file paths emitted into // the PE / PDB are valid file paths because pathmap can be used to create deliberately // illegal names if (!PathUtilities.IsValidFilePath(finalPdbFilePath)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.FTL_InvalidInputFileName, Location.None, finalPdbFilePath)); } var moduleBeingBuilt = compilation.CheckOptionsAndCreateModuleBuilder( diagnostics, Arguments.ManifestResources, emitOptions, debugEntryPoint: null, sourceLinkStream: sourceLinkStreamDisposerOpt?.Stream, embeddedTexts: embeddedTexts, testData: null, cancellationToken: cancellationToken); if (moduleBeingBuilt != null) { bool success; try { success = compilation.CompileMethods( moduleBeingBuilt, Arguments.EmitPdb, emitOptions.EmitMetadataOnly, emitOptions.EmitTestCoverageData, diagnostics, filterOpt: null, cancellationToken: cancellationToken); // Prior to generating the xml documentation file, // we apply programmatic suppressions for compiler warnings from diagnostic suppressors. // If there are still any unsuppressed errors or warnings escalated to errors // then we bail out from generating the documentation file. // This maintains the compiler invariant that xml documentation file should not be // generated in presence of diagnostics that break the build. if (analyzerDriver != null && !diagnostics.IsEmptyWithoutResolution) { analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { // NOTE: as native compiler does, we generate the documentation file // NOTE: 'in place', replacing the contents of the file if it exists NoThrowStreamDisposer? xmlStreamDisposerOpt = null; if (finalXmlFilePath != null) { var xmlStreamOpt = OpenFile(finalXmlFilePath, diagnostics, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); if (xmlStreamOpt == null) { return; } try { xmlStreamOpt.SetLength(0); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, finalXmlFilePath, diagnostics); return; } xmlStreamDisposerOpt = new NoThrowStreamDisposer( xmlStreamOpt, finalXmlFilePath, diagnostics, MessageProvider); } using (xmlStreamDisposerOpt) { using (var win32ResourceStreamOpt = GetWin32Resources(FileSystem, MessageProvider, Arguments, compilation, diagnostics)) { if (HasUnsuppressableErrors(diagnostics)) { return; } success = compilation.GenerateResourcesAndDocumentationComments( moduleBeingBuilt, xmlStreamDisposerOpt?.Stream, win32ResourceStreamOpt, useRawWin32Resources: false, emitOptions.OutputNameOverride, diagnostics, cancellationToken); } } if (xmlStreamDisposerOpt?.HasFailedToDispose == true) { return; } // only report unused usings if we have success. if (success) { compilation.ReportUnusedImports(diagnostics, cancellationToken); } } compilation.CompleteTrees(null); if (analyzerDriver != null) { // GetDiagnosticsAsync is called after ReportUnusedImports // since that method calls EventQueue.TryComplete. Without // TryComplete, we may miss diagnostics. var hostDiagnostics = analyzerDriver.GetDiagnosticsAsync(compilation).Result; diagnostics.AddRange(hostDiagnostics); if (!diagnostics.IsEmptyWithoutResolution) { // Apply diagnostic suppressions for analyzer and/or compiler diagnostics from diagnostic suppressors. analyzerDriver.ApplyProgrammaticSuppressions(diagnostics, compilation); } } } finally { moduleBeingBuilt.CompilationFinished(); } if (HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { var peStreamProvider = new CompilerEmitStreamProvider(this, finalPeFilePath); var pdbStreamProviderOpt = Arguments.EmitPdbFile ? new CompilerEmitStreamProvider(this, finalPdbFilePath) : null; string? finalRefPeFilePath = Arguments.OutputRefFilePath; var refPeStreamProviderOpt = finalRefPeFilePath != null ? new CompilerEmitStreamProvider(this, finalRefPeFilePath) : null; RSAParameters? privateKeyOpt = null; if (compilation.Options.StrongNameProvider != null && compilation.SignUsingBuilder && !compilation.Options.PublicSign) { privateKeyOpt = compilation.StrongNameKeys.PrivateKey; } // If we serialize to a PE stream we need to record the fallback encoding if it was used // so the compilation can be recreated. emitOptions = emitOptions.WithFallbackSourceFileEncoding(GetFallbackEncoding()); success = compilation.SerializeToPeStream( moduleBeingBuilt, peStreamProvider, refPeStreamProviderOpt, pdbStreamProviderOpt, rebuildData: null, testSymWriterFactory: null, diagnostics: diagnostics, emitOptions: emitOptions, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken); peStreamProvider.Close(diagnostics); refPeStreamProviderOpt?.Close(diagnostics); pdbStreamProviderOpt?.Close(diagnostics); if (success && touchedFilesLogger != null) { if (pdbStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalPdbFilePath); } if (refPeStreamProviderOpt != null) { touchedFilesLogger.AddWritten(finalRefPeFilePath!); } touchedFilesLogger.AddWritten(finalPeFilePath); } } } if (HasUnsuppressableErrors(diagnostics)) { return; } } finally { sourceLinkStreamDisposerOpt?.Dispose(); } if (sourceLinkStreamDisposerOpt?.HasFailedToDispose == true) { return; } cancellationToken.ThrowIfCancellationRequested(); if (analyzerExceptionDiagnostics != null) { diagnostics.AddRange(analyzerExceptionDiagnostics); if (HasUnsuppressableErrors(analyzerExceptionDiagnostics)) { return; } } cancellationToken.ThrowIfCancellationRequested(); if (!WriteTouchedFiles(diagnostics, touchedFilesLogger, finalXmlFilePath)) { return; } } // virtual for testing protected virtual Diagnostics.AnalyzerOptions CreateAnalyzerOptions( ImmutableArray<AdditionalText> additionalTextFiles, AnalyzerConfigOptionsProvider analyzerConfigOptionsProvider) => new Diagnostics.AnalyzerOptions(additionalTextFiles, analyzerConfigOptionsProvider); private bool WriteTouchedFiles(DiagnosticBag diagnostics, TouchedFileLogger? touchedFilesLogger, string? finalXmlFilePath) { if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger != null); if (finalXmlFilePath != null) { touchedFilesLogger.AddWritten(finalXmlFilePath); } string readFilesPath = Arguments.TouchedFilesPath + ".read"; string writtenFilesPath = Arguments.TouchedFilesPath + ".write"; var readStream = OpenFile(readFilesPath, diagnostics, mode: FileMode.OpenOrCreate); var writtenStream = OpenFile(writtenFilesPath, diagnostics, mode: FileMode.OpenOrCreate); if (readStream == null || writtenStream == null) { return false; } string? filePath = null; try { filePath = readFilesPath; using (var writer = new StreamWriter(readStream)) { touchedFilesLogger.WriteReadPaths(writer); } filePath = writtenFilesPath; using (var writer = new StreamWriter(writtenStream)) { touchedFilesLogger.WriteWrittenPaths(writer); } } catch (Exception e) { Debug.Assert(filePath != null); MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return false; } } return true; } protected virtual ImmutableArray<AdditionalTextFile> ResolveAdditionalFilesFromArguments(List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, TouchedFileLogger? touchedFilesLogger) { var builder = ImmutableArray.CreateBuilder<AdditionalTextFile>(); foreach (var file in Arguments.AdditionalFiles) { builder.Add(new AdditionalTextFile(file, this)); } return builder.ToImmutableArray(); } private static void ReportAnalyzerExecutionTime(TextWriter consoleOutput, AnalyzerDriver analyzerDriver, CultureInfo culture, bool isConcurrentBuild) { Debug.Assert(analyzerDriver.AnalyzerExecutionTimes != null); if (analyzerDriver.AnalyzerExecutionTimes.IsEmpty) { return; } var totalAnalyzerExecutionTime = analyzerDriver.AnalyzerExecutionTimes.Sum(kvp => kvp.Value.TotalSeconds); Func<double, string> getFormattedTime = d => d.ToString("##0.000", culture); consoleOutput.WriteLine(); consoleOutput.WriteLine(string.Format(CodeAnalysisResources.AnalyzerTotalExecutionTime, getFormattedTime(totalAnalyzerExecutionTime))); if (isConcurrentBuild) { consoleOutput.WriteLine(CodeAnalysisResources.MultithreadedAnalyzerExecutionNote); } var analyzersByAssembly = analyzerDriver.AnalyzerExecutionTimes .GroupBy(kvp => kvp.Key.GetType().GetTypeInfo().Assembly) .OrderByDescending(kvp => kvp.Sum(entry => entry.Value.Ticks)); consoleOutput.WriteLine(); getFormattedTime = d => d < 0.001 ? string.Format(culture, "{0,8:<0.000}", 0.001) : string.Format(culture, "{0,8:##0.000}", d); Func<int, string> getFormattedPercentage = i => string.Format("{0,5}", i < 1 ? "<1" : i.ToString()); Func<string?, string> getFormattedAnalyzerName = s => " " + s; // Table header var analyzerTimeColumn = string.Format("{0,8}", CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader); var analyzerPercentageColumn = string.Format("{0,5}", "%"); var analyzerNameColumn = getFormattedAnalyzerName(CodeAnalysisResources.AnalyzerNameColumnHeader); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Table rows grouped by assembly. foreach (var analyzerGroup in analyzersByAssembly) { var executionTime = analyzerGroup.Sum(kvp => kvp.Value.TotalSeconds); var percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); analyzerNameColumn = getFormattedAnalyzerName(analyzerGroup.Key.FullName); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); // Rows for each diagnostic analyzer in the assembly. foreach (var kvp in analyzerGroup.OrderByDescending(kvp => kvp.Value)) { executionTime = kvp.Value.TotalSeconds; percentage = (int)(executionTime * 100 / totalAnalyzerExecutionTime); analyzerTimeColumn = getFormattedTime(executionTime); analyzerPercentageColumn = getFormattedPercentage(percentage); var analyzerIds = string.Join(", ", kvp.Key.SupportedDiagnostics.Select(d => d.Id).Distinct().OrderBy(id => id)); analyzerNameColumn = getFormattedAnalyzerName($" {kvp.Key} ({analyzerIds})"); consoleOutput.WriteLine(analyzerTimeColumn + analyzerPercentageColumn + analyzerNameColumn); } consoleOutput.WriteLine(); } } /// <summary> /// Returns the name with which the assembly should be output /// </summary> protected abstract string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken); private Stream? OpenFile( string filePath, DiagnosticBag diagnostics, FileMode mode = FileMode.Open, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.None) { try { return FileSystem.OpenFile(filePath, mode, access, share); } catch (Exception e) { MessageProvider.ReportStreamWriteException(e, filePath, diagnostics); return null; } } // internal for testing internal static Stream? GetWin32ResourcesInternal( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, out IEnumerable<DiagnosticInfo> errors) { var diagnostics = DiagnosticBag.GetInstance(); var stream = GetWin32Resources(fileSystem, messageProvider, arguments, compilation, diagnostics); errors = diagnostics.ToReadOnlyAndFree().SelectAsArray(diag => new DiagnosticInfo(messageProvider, diag.IsWarningAsError, diag.Code, (object[])diag.Arguments)); return stream; } private static Stream? GetWin32Resources( ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, CommandLineArguments arguments, Compilation compilation, DiagnosticBag diagnostics) { if (arguments.Win32ResourceFile != null) { return OpenStream(fileSystem, messageProvider, arguments.Win32ResourceFile, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Resource, diagnostics); } using (Stream? manifestStream = OpenManifestStream(fileSystem, messageProvider, compilation.Options.OutputKind, arguments, diagnostics)) { using (Stream? iconStream = OpenStream(fileSystem, messageProvider, arguments.Win32Icon, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Icon, diagnostics)) { try { return compilation.CreateDefaultWin32Resources(true, arguments.NoWin32Manifest, manifestStream, iconStream); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_ErrorBuildingWin32Resource, Location.None, ex.Message)); } } } return null; } private static Stream? OpenManifestStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, OutputKind outputKind, CommandLineArguments arguments, DiagnosticBag diagnostics) { return outputKind.IsNetModule() ? null : OpenStream(fileSystem, messageProvider, arguments.Win32Manifest, arguments.BaseDirectory, messageProvider.ERR_CantOpenWin32Manifest, diagnostics); } private static Stream? OpenStream(ICommonCompilerFileSystem fileSystem, CommonMessageProvider messageProvider, string? path, string? baseDirectory, int errorCode, DiagnosticBag diagnostics) { if (path == null) { return null; } string? fullPath = ResolveRelativePath(messageProvider, path, baseDirectory, diagnostics); if (fullPath == null) { return null; } try { return fileSystem.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception ex) { diagnostics.Add(messageProvider.CreateDiagnostic(errorCode, Location.None, fullPath, ex.Message)); } return null; } private static string? ResolveRelativePath(CommonMessageProvider messageProvider, string path, string? baseDirectory, DiagnosticBag diagnostics) { string? fullPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (fullPath == null) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.FTL_InvalidInputFileName, Location.None, path ?? "")); } return fullPath; } internal static bool TryGetCompilerDiagnosticCode(string diagnosticId, string expectedPrefix, out uint code) { code = 0; return diagnosticId.StartsWith(expectedPrefix, StringComparison.Ordinal) && uint.TryParse(diagnosticId.Substring(expectedPrefix.Length), out code); } /// <summary> /// When overridden by a derived class, this property can override the current thread's /// CurrentUICulture property for diagnostic message resource lookups. /// </summary> protected virtual CultureInfo Culture { get { return Arguments.PreferredUILang ?? CultureInfo.CurrentUICulture; } } private static void EmitDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { var key = CreateDeterminismKey(args, rawArgs, baseDirectory, parser); var filePath = Path.Combine(args.OutputDirectory, args.OutputFileName + ".key"); using (var stream = File.Create(filePath)) { var bytes = Encoding.UTF8.GetBytes(key); stream.Write(bytes, 0, bytes.Length); } } /// <summary> /// The string returned from this function represents the inputs to the compiler which impact determinism. It is /// meant to be inline with the specification here: /// /// - https://github.com/dotnet/roslyn/blob/main/docs/compilers/Deterministic%20Inputs.md /// /// Issue #8193 tracks filling this out to the full specification. /// /// https://github.com/dotnet/roslyn/issues/8193 /// </summary> private static string CreateDeterminismKey(CommandLineArguments args, string[] rawArgs, string baseDirectory, CommandLineParser parser) { List<Diagnostic> diagnostics = new List<Diagnostic>(); var flattenedArgs = ArrayBuilder<string>.GetInstance(); parser.FlattenArgs(rawArgs, diagnostics, flattenedArgs, null, baseDirectory); var builder = new StringBuilder(); var name = !string.IsNullOrEmpty(args.OutputFileName) ? Path.GetFileNameWithoutExtension(Path.GetFileName(args.OutputFileName)) : $"no-output-name-{Guid.NewGuid().ToString()}"; builder.AppendLine($"{name}"); builder.AppendLine($"Command Line:"); foreach (var current in flattenedArgs) { builder.AppendLine($"\t{current}"); } builder.AppendLine("Source Files:"); var hash = MD5.Create(); foreach (var sourceFile in args.SourceFiles) { var sourceFileName = Path.GetFileName(sourceFile.Path); string hashValue; try { var bytes = File.ReadAllBytes(sourceFile.Path); var hashBytes = hash.ComputeHash(bytes); var data = BitConverter.ToString(hashBytes); hashValue = data.Replace("-", ""); } catch (Exception ex) { hashValue = $"Could not compute {ex.Message}"; } builder.AppendLine($"\t{sourceFileName} - {hashValue}"); } flattenedArgs.Free(); return builder.ToString(); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.NodeNameGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeNameGenerator CreateNodeNameGenerator() => new NodeNameGenerator(); private class NodeNameGenerator : AbstractNodeNameGenerator { protected override bool IsNameableNode(SyntaxNode node) => CSharpCodeModelService.IsNameableNode(node); private static void AppendName(StringBuilder builder, NameSyntax name) { if (name.Kind() == SyntaxKind.QualifiedName) { AppendName(builder, ((QualifiedNameSyntax)name).Left); } switch (name.Kind()) { case SyntaxKind.IdentifierName: AppendDotIfNeeded(builder); builder.Append(((IdentifierNameSyntax)name).Identifier.ValueText); break; case SyntaxKind.GenericName: var genericName = (GenericNameSyntax)name; AppendDotIfNeeded(builder); builder.Append(genericName.Identifier.ValueText); AppendArity(builder, genericName.Arity); break; case SyntaxKind.AliasQualifiedName: var aliasQualifiedName = (AliasQualifiedNameSyntax)name; AppendName(builder, aliasQualifiedName.Alias); builder.Append("::"); AppendName(builder, aliasQualifiedName.Name); break; case SyntaxKind.QualifiedName: AppendName(builder, ((QualifiedNameSyntax)name).Right); break; } } private static void AppendTypeName(StringBuilder builder, TypeSyntax type) { if (type is NameSyntax name) { AppendName(builder, name); } else { switch (type.Kind()) { case SyntaxKind.PredefinedType: builder.Append(((PredefinedTypeSyntax)type).Keyword.ValueText); break; case SyntaxKind.ArrayType: var arrayType = (ArrayTypeSyntax)type; AppendTypeName(builder, arrayType.ElementType); var specifiers = arrayType.RankSpecifiers; for (var i = 0; i < specifiers.Count; i++) { builder.Append('['); var specifier = specifiers[i]; if (specifier.Rank > 1) { builder.Append(',', specifier.Rank - 1); } builder.Append(']'); } break; case SyntaxKind.PointerType: AppendTypeName(builder, ((PointerTypeSyntax)type).ElementType); builder.Append('*'); break; case SyntaxKind.NullableType: AppendTypeName(builder, ((NullableTypeSyntax)type).ElementType); builder.Append('?'); break; } } } private static void AppendParameterList(StringBuilder builder, BaseParameterListSyntax parameterList) { builder.Append(parameterList is BracketedParameterListSyntax ? '[' : '('); var firstSeen = false; foreach (var parameter in parameterList.Parameters) { if (firstSeen) { builder.Append(","); } if (parameter.Modifiers.Any(SyntaxKind.RefKeyword)) { builder.Append("ref "); } else if (parameter.Modifiers.Any(SyntaxKind.OutKeyword)) { builder.Append("out "); } else if (parameter.Modifiers.Any(SyntaxKind.ParamsKeyword)) { builder.Append("params "); } AppendTypeName(builder, parameter.Type); firstSeen = true; } builder.Append(parameterList is BracketedParameterListSyntax ? ']' : ')'); } private static void AppendOperatorName(StringBuilder builder, SyntaxKind kind) { var name = "#op_" + kind.ToString(); if (name.EndsWith("Keyword", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - 7); } else if (name.EndsWith("Token", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - 5); } builder.Append(name); } protected override void AppendNodeName(StringBuilder builder, SyntaxNode node) { Debug.Assert(node != null); Debug.Assert(IsNameableNode(node)); AppendDotIfNeeded(builder); switch (node.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node; AppendName(builder, namespaceDeclaration.Name); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; builder.Append(typeDeclaration.Identifier.ValueText); AppendArity(builder, typeDeclaration.Arity); break; case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; builder.Append(enumDeclaration.Identifier.ValueText); break; case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; builder.Append(delegateDeclaration.Identifier.ValueText); AppendArity(builder, delegateDeclaration.Arity); break; case SyntaxKind.EnumMemberDeclaration: var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node; builder.Append(enumMemberDeclaration.Identifier.ValueText); break; case SyntaxKind.VariableDeclarator: var variableDeclarator = (VariableDeclaratorSyntax)node; builder.Append(variableDeclarator.Identifier.ValueText); break; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; builder.Append(methodDeclaration.Identifier.ValueText); AppendArity(builder, methodDeclaration.Arity); AppendParameterList(builder, methodDeclaration.ParameterList); break; case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; AppendOperatorName(builder, operatorDeclaration.OperatorToken.Kind()); AppendParameterList(builder, operatorDeclaration.ParameterList); break; case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; AppendOperatorName(builder, conversionOperatorDeclaration.ImplicitOrExplicitKeyword.Kind()); builder.Append('_'); AppendTypeName(builder, conversionOperatorDeclaration.Type); AppendParameterList(builder, conversionOperatorDeclaration.ParameterList); break; case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; builder.Append(constructorDeclaration.Modifiers.Any(SyntaxKind.StaticKeyword) ? "#sctor" : "#ctor"); AppendParameterList(builder, constructorDeclaration.ParameterList); break; case SyntaxKind.DestructorDeclaration: builder.Append("#dtor()"); break; case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; builder.Append("#this"); AppendParameterList(builder, indexerDeclaration.ParameterList); break; case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; builder.Append(propertyDeclaration.Identifier.ValueText); break; case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; builder.Append(eventDeclaration.Identifier.ValueText); break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeNameGenerator CreateNodeNameGenerator() => new NodeNameGenerator(); private class NodeNameGenerator : AbstractNodeNameGenerator { protected override bool IsNameableNode(SyntaxNode node) => CSharpCodeModelService.IsNameableNode(node); private static void AppendName(StringBuilder builder, NameSyntax name) { if (name.Kind() == SyntaxKind.QualifiedName) { AppendName(builder, ((QualifiedNameSyntax)name).Left); } switch (name.Kind()) { case SyntaxKind.IdentifierName: AppendDotIfNeeded(builder); builder.Append(((IdentifierNameSyntax)name).Identifier.ValueText); break; case SyntaxKind.GenericName: var genericName = (GenericNameSyntax)name; AppendDotIfNeeded(builder); builder.Append(genericName.Identifier.ValueText); AppendArity(builder, genericName.Arity); break; case SyntaxKind.AliasQualifiedName: var aliasQualifiedName = (AliasQualifiedNameSyntax)name; AppendName(builder, aliasQualifiedName.Alias); builder.Append("::"); AppendName(builder, aliasQualifiedName.Name); break; case SyntaxKind.QualifiedName: AppendName(builder, ((QualifiedNameSyntax)name).Right); break; } } private static void AppendTypeName(StringBuilder builder, TypeSyntax type) { if (type is NameSyntax name) { AppendName(builder, name); } else { switch (type.Kind()) { case SyntaxKind.PredefinedType: builder.Append(((PredefinedTypeSyntax)type).Keyword.ValueText); break; case SyntaxKind.ArrayType: var arrayType = (ArrayTypeSyntax)type; AppendTypeName(builder, arrayType.ElementType); var specifiers = arrayType.RankSpecifiers; for (var i = 0; i < specifiers.Count; i++) { builder.Append('['); var specifier = specifiers[i]; if (specifier.Rank > 1) { builder.Append(',', specifier.Rank - 1); } builder.Append(']'); } break; case SyntaxKind.PointerType: AppendTypeName(builder, ((PointerTypeSyntax)type).ElementType); builder.Append('*'); break; case SyntaxKind.NullableType: AppendTypeName(builder, ((NullableTypeSyntax)type).ElementType); builder.Append('?'); break; } } } private static void AppendParameterList(StringBuilder builder, BaseParameterListSyntax parameterList) { builder.Append(parameterList is BracketedParameterListSyntax ? '[' : '('); var firstSeen = false; foreach (var parameter in parameterList.Parameters) { if (firstSeen) { builder.Append(","); } if (parameter.Modifiers.Any(SyntaxKind.RefKeyword)) { builder.Append("ref "); } else if (parameter.Modifiers.Any(SyntaxKind.OutKeyword)) { builder.Append("out "); } else if (parameter.Modifiers.Any(SyntaxKind.ParamsKeyword)) { builder.Append("params "); } AppendTypeName(builder, parameter.Type); firstSeen = true; } builder.Append(parameterList is BracketedParameterListSyntax ? ']' : ')'); } private static void AppendOperatorName(StringBuilder builder, SyntaxKind kind) { var name = "#op_" + kind.ToString(); if (name.EndsWith("Keyword", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - 7); } else if (name.EndsWith("Token", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - 5); } builder.Append(name); } protected override void AppendNodeName(StringBuilder builder, SyntaxNode node) { Debug.Assert(node != null); Debug.Assert(IsNameableNode(node)); AppendDotIfNeeded(builder); switch (node.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)node; AppendName(builder, namespaceDeclaration.Name); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; builder.Append(typeDeclaration.Identifier.ValueText); AppendArity(builder, typeDeclaration.Arity); break; case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; builder.Append(enumDeclaration.Identifier.ValueText); break; case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; builder.Append(delegateDeclaration.Identifier.ValueText); AppendArity(builder, delegateDeclaration.Arity); break; case SyntaxKind.EnumMemberDeclaration: var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node; builder.Append(enumMemberDeclaration.Identifier.ValueText); break; case SyntaxKind.VariableDeclarator: var variableDeclarator = (VariableDeclaratorSyntax)node; builder.Append(variableDeclarator.Identifier.ValueText); break; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; builder.Append(methodDeclaration.Identifier.ValueText); AppendArity(builder, methodDeclaration.Arity); AppendParameterList(builder, methodDeclaration.ParameterList); break; case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; AppendOperatorName(builder, operatorDeclaration.OperatorToken.Kind()); AppendParameterList(builder, operatorDeclaration.ParameterList); break; case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; AppendOperatorName(builder, conversionOperatorDeclaration.ImplicitOrExplicitKeyword.Kind()); builder.Append('_'); AppendTypeName(builder, conversionOperatorDeclaration.Type); AppendParameterList(builder, conversionOperatorDeclaration.ParameterList); break; case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; builder.Append(constructorDeclaration.Modifiers.Any(SyntaxKind.StaticKeyword) ? "#sctor" : "#ctor"); AppendParameterList(builder, constructorDeclaration.ParameterList); break; case SyntaxKind.DestructorDeclaration: builder.Append("#dtor()"); break; case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; builder.Append("#this"); AppendParameterList(builder, indexerDeclaration.ParameterList); break; case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; builder.Append(propertyDeclaration.Identifier.ValueText); break; case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; builder.Append(eventDeclaration.Identifier.ValueText); break; } } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/FixAllSuggestedAction.FixAllCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class FixAllSuggestedAction { private sealed partial class FixAllCodeAction : FixSomeCodeAction { public FixAllCodeAction(FixAllState fixAllState) : base(fixAllState, showPreviewChangesDialog: true) { } public override string Title => this.FixAllState.Scope switch { FixAllScope.Document => FeaturesResources.Document, FixAllScope.Project => FeaturesResources.Project, FixAllScope.Solution => FeaturesResources.Solution, _ => throw new NotSupportedException(), }; internal override string Message => FeaturesResources.Computing_fix_all_occurrences_code_fix; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class FixAllSuggestedAction { private sealed partial class FixAllCodeAction : FixSomeCodeAction { public FixAllCodeAction(FixAllState fixAllState) : base(fixAllState, showPreviewChangesDialog: true) { } public override string Title => this.FixAllState.Scope switch { FixAllScope.Document => FeaturesResources.Document, FixAllScope.Project => FeaturesResources.Project, FixAllScope.Solution => FeaturesResources.Solution, _ => throw new NotSupportedException(), }; internal override string Message => FeaturesResources.Computing_fix_all_occurrences_code_fix; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/ImportRecord.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct ImportRecord { public readonly ImportTargetKind TargetKind; public readonly string? Alias; // target type of a type import (C#) public readonly ITypeSymbolInternal? TargetType; // target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB) public readonly string? TargetString; // target assembly of a namespace import (C#, Portable) public readonly IAssemblySymbolInternal? TargetAssembly; // target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB) public readonly string? TargetAssemblyAlias; public ImportRecord( ImportTargetKind targetKind, string? alias = null, ITypeSymbolInternal? targetType = null, string? targetString = null, IAssemblySymbolInternal? targetAssembly = null, string? targetAssemblyAlias = null) { TargetKind = targetKind; Alias = alias; TargetType = targetType; TargetString = targetString; TargetAssembly = targetAssembly; TargetAssemblyAlias = targetAssemblyAlias; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct ImportRecord { public readonly ImportTargetKind TargetKind; public readonly string? Alias; // target type of a type import (C#) public readonly ITypeSymbolInternal? TargetType; // target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB) public readonly string? TargetString; // target assembly of a namespace import (C#, Portable) public readonly IAssemblySymbolInternal? TargetAssembly; // target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB) public readonly string? TargetAssemblyAlias; public ImportRecord( ImportTargetKind targetKind, string? alias = null, ITypeSymbolInternal? targetType = null, string? targetString = null, IAssemblySymbolInternal? targetAssembly = null, string? targetAssemblyAlias = null) { TargetKind = targetKind; Alias = alias; TargetType = targetType; TargetString = targetString; TargetAssembly = targetAssembly; TargetAssemblyAlias = targetAssemblyAlias; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/Portable/StrongName/DesktopStrongNameProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Cci; using Microsoft.CodeAnalysis.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides strong name and signs source assemblies. /// </summary> public class DesktopStrongNameProvider : StrongNameProvider { // This exception is only used to detect when the acquisition of IClrStrongName fails // and the likely reason is that we're running on CoreCLR on a non-Windows platform. // The place where the acquisition fails does not have access to localization, // so we can't throw some generic exception with a localized message. // So this is sort of a token for the eventual message to be generated. // The path from where this is thrown to where it is caught is all internal, // so there's no chance of an API consumer seeing it. internal sealed class ClrStrongNameMissingException : Exception { } private readonly ImmutableArray<string> _keyFileSearchPaths; internal override StrongNameFileSystem FileSystem { get; } public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths) : this(keyFileSearchPaths, StrongNameFileSystem.Instance) { } /// <summary> /// Creates an instance of <see cref="DesktopStrongNameProvider"/>. /// </summary> /// <param name="tempPath">Path to use for any temporary file generation.</param> /// <param name="keyFileSearchPaths">An ordered set of fully qualified paths which are searched when locating a cryptographic key file.</param> public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths = default, string? tempPath = null) : this(keyFileSearchPaths, tempPath == null ? StrongNameFileSystem.Instance : new StrongNameFileSystem(tempPath)) { } internal DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths, StrongNameFileSystem strongNameFileSystem) { if (!keyFileSearchPaths.IsDefault && keyFileSearchPaths.Any(path => !PathUtilities.IsAbsolute(path))) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(keyFileSearchPaths)); } FileSystem = strongNameFileSystem ?? StrongNameFileSystem.Instance; _keyFileSearchPaths = keyFileSearchPaths.NullToEmpty(); } internal override StrongNameKeys CreateKeys(string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) { var keyPair = default(ImmutableArray<byte>); var publicKey = default(ImmutableArray<byte>); string? container = null; if (!string.IsNullOrEmpty(keyFilePath)) { try { string? resolvedKeyFile = ResolveStrongNameKeyFile(keyFilePath, FileSystem, _keyFileSearchPaths); if (resolvedKeyFile == null) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, CodeAnalysisResources.FileNotFound)); } Debug.Assert(PathUtilities.IsAbsolute(resolvedKeyFile)); var fileContent = ImmutableArray.Create(FileSystem.ReadAllBytes(resolvedKeyFile)); return StrongNameKeys.CreateHelper(fileContent, keyFilePath, hasCounterSignature); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, ex.Message)); } } else if (!string.IsNullOrEmpty(keyContainerName)) { try { ReadKeysFromContainer(keyContainerName, out publicKey); container = keyContainerName; } catch (ClrStrongNameMissingException) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)))); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, ex.Message)); } } return new StrongNameKeys(keyPair, publicKey, privateKey: null, container, keyFilePath, hasCounterSignature); } /// <summary> /// Resolves assembly strong name key file path. /// </summary> /// <returns>Normalized key file path or null if not found.</returns> internal static string? ResolveStrongNameKeyFile(string path, StrongNameFileSystem fileSystem, ImmutableArray<string> keyFileSearchPaths) { // Dev11: key path is simply appended to the search paths, even if it starts with the current (parent) directory ("." or ".."). // This is different from PathUtilities.ResolveRelativePath. if (PathUtilities.IsAbsolute(path)) { if (fileSystem.FileExists(path)) { return FileUtilities.TryNormalizeAbsolutePath(path); } return path; } foreach (var searchPath in keyFileSearchPaths) { string? combinedPath = PathUtilities.CombineAbsoluteAndRelativePaths(searchPath, path); Debug.Assert(combinedPath == null || PathUtilities.IsAbsolute(combinedPath)); if (fileSystem.FileExists(combinedPath)) { return FileUtilities.TryNormalizeAbsolutePath(combinedPath!); } } return null; } internal virtual void ReadKeysFromContainer(string keyContainer, out ImmutableArray<byte> publicKey) { try { publicKey = GetPublicKey(keyContainer); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message); } } internal override void SignFile(StrongNameKeys keys, string filePath) { Debug.Assert(string.IsNullOrEmpty(keys.KeyFilePath) != string.IsNullOrEmpty(keys.KeyContainer)); if (!string.IsNullOrEmpty(keys.KeyFilePath)) { Sign(filePath, keys.KeyPair); } else { Sign(filePath, keys.KeyContainer!); } } internal override void SignBuilder(ExtendedPEBuilder peBuilder, BlobBuilder peBlob, RSAParameters privateKey) { peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKey)); } // EDMAURER in the event that the key is supplied as a file, // this type could get an instance member that caches the file // contents to avoid reading the file twice - once to get the // public key to establish the assembly name and another to do // the actual signing internal virtual IClrStrongName GetStrongNameInterface() { try { return ClrStrongName.GetInstance(); } catch (MarshalDirectiveException) when (PathUtilities.IsUnixLikePlatform) { // CoreCLR, when not on Windows, doesn't support IClrStrongName (or COM in general). // This is really hard to detect/predict without false positives/negatives. // It turns out that CoreCLR throws a MarshalDirectiveException when attempting // to get the interface (Message "Cannot marshal 'return value': Unknown error."), // so just catch that and state that it's not supported. // We're deep in a try block that reports the exception's Message as part of a diagnostic. // This exception will skip through the IOException wrapping by `Sign` (in this class), // then caught by Compilation.SerializeToPeStream or DesktopStringNameProvider.CreateKeys throw new ClrStrongNameMissingException(); } } internal ImmutableArray<byte> GetPublicKey(string keyContainer) { IClrStrongName strongName = GetStrongNameInterface(); IntPtr keyBlob; int keyBlobByteCount; strongName.StrongNameGetPublicKey(keyContainer, pbKeyBlob: default, 0, out keyBlob, out keyBlobByteCount); byte[] pubKey = new byte[keyBlobByteCount]; Marshal.Copy(keyBlob, pubKey, 0, keyBlobByteCount); strongName.StrongNameFreeBuffer(keyBlob); return pubKey.AsImmutableOrNull(); } /// <exception cref="IOException"/> private void Sign(string filePath, string keyName) { try { IClrStrongName strongName = GetStrongNameInterface(); strongName.StrongNameSignatureGeneration(filePath, keyName, IntPtr.Zero, 0, null, pcbSignatureBlob: out _); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } private unsafe void Sign(string filePath, ImmutableArray<byte> keyPair) { try { IClrStrongName strongName = GetStrongNameInterface(); fixed (byte* pinned = keyPair.ToArray()) { strongName.StrongNameSignatureGeneration(filePath, null, (IntPtr)pinned, keyPair.Length, null, pcbSignatureBlob: out _); } } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } public override int GetHashCode() { return Hash.CombineValues(_keyFileSearchPaths, StringComparer.Ordinal); } public override bool Equals(object? obj) { if (obj is null || GetType() != obj.GetType()) { return false; } var other = (DesktopStrongNameProvider)obj; if (FileSystem != other.FileSystem) { return false; } if (!_keyFileSearchPaths.SequenceEqual(other._keyFileSearchPaths, StringComparer.Ordinal)) { 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.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Cci; using Microsoft.CodeAnalysis.Interop; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides strong name and signs source assemblies. /// </summary> public class DesktopStrongNameProvider : StrongNameProvider { // This exception is only used to detect when the acquisition of IClrStrongName fails // and the likely reason is that we're running on CoreCLR on a non-Windows platform. // The place where the acquisition fails does not have access to localization, // so we can't throw some generic exception with a localized message. // So this is sort of a token for the eventual message to be generated. // The path from where this is thrown to where it is caught is all internal, // so there's no chance of an API consumer seeing it. internal sealed class ClrStrongNameMissingException : Exception { } private readonly ImmutableArray<string> _keyFileSearchPaths; internal override StrongNameFileSystem FileSystem { get; } public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths) : this(keyFileSearchPaths, StrongNameFileSystem.Instance) { } /// <summary> /// Creates an instance of <see cref="DesktopStrongNameProvider"/>. /// </summary> /// <param name="tempPath">Path to use for any temporary file generation.</param> /// <param name="keyFileSearchPaths">An ordered set of fully qualified paths which are searched when locating a cryptographic key file.</param> public DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths = default, string? tempPath = null) : this(keyFileSearchPaths, tempPath == null ? StrongNameFileSystem.Instance : new StrongNameFileSystem(tempPath)) { } internal DesktopStrongNameProvider(ImmutableArray<string> keyFileSearchPaths, StrongNameFileSystem strongNameFileSystem) { if (!keyFileSearchPaths.IsDefault && keyFileSearchPaths.Any(path => !PathUtilities.IsAbsolute(path))) { throw new ArgumentException(CodeAnalysisResources.AbsolutePathExpected, nameof(keyFileSearchPaths)); } FileSystem = strongNameFileSystem ?? StrongNameFileSystem.Instance; _keyFileSearchPaths = keyFileSearchPaths.NullToEmpty(); } internal override StrongNameKeys CreateKeys(string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) { var keyPair = default(ImmutableArray<byte>); var publicKey = default(ImmutableArray<byte>); string? container = null; if (!string.IsNullOrEmpty(keyFilePath)) { try { string? resolvedKeyFile = ResolveStrongNameKeyFile(keyFilePath, FileSystem, _keyFileSearchPaths); if (resolvedKeyFile == null) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, CodeAnalysisResources.FileNotFound)); } Debug.Assert(PathUtilities.IsAbsolute(resolvedKeyFile)); var fileContent = ImmutableArray.Create(FileSystem.ReadAllBytes(resolvedKeyFile)); return StrongNameKeys.CreateHelper(fileContent, keyFilePath, hasCounterSignature); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetKeyFileError(messageProvider, keyFilePath, ex.Message)); } } else if (!string.IsNullOrEmpty(keyContainerName)) { try { ReadKeysFromContainer(keyContainerName, out publicKey); container = keyContainerName; } catch (ClrStrongNameMissingException) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)))); } catch (Exception ex) { return new StrongNameKeys(StrongNameKeys.GetContainerError(messageProvider, keyContainerName, ex.Message)); } } return new StrongNameKeys(keyPair, publicKey, privateKey: null, container, keyFilePath, hasCounterSignature); } /// <summary> /// Resolves assembly strong name key file path. /// </summary> /// <returns>Normalized key file path or null if not found.</returns> internal static string? ResolveStrongNameKeyFile(string path, StrongNameFileSystem fileSystem, ImmutableArray<string> keyFileSearchPaths) { // Dev11: key path is simply appended to the search paths, even if it starts with the current (parent) directory ("." or ".."). // This is different from PathUtilities.ResolveRelativePath. if (PathUtilities.IsAbsolute(path)) { if (fileSystem.FileExists(path)) { return FileUtilities.TryNormalizeAbsolutePath(path); } return path; } foreach (var searchPath in keyFileSearchPaths) { string? combinedPath = PathUtilities.CombineAbsoluteAndRelativePaths(searchPath, path); Debug.Assert(combinedPath == null || PathUtilities.IsAbsolute(combinedPath)); if (fileSystem.FileExists(combinedPath)) { return FileUtilities.TryNormalizeAbsolutePath(combinedPath!); } } return null; } internal virtual void ReadKeysFromContainer(string keyContainer, out ImmutableArray<byte> publicKey) { try { publicKey = GetPublicKey(keyContainer); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message); } } internal override void SignFile(StrongNameKeys keys, string filePath) { Debug.Assert(string.IsNullOrEmpty(keys.KeyFilePath) != string.IsNullOrEmpty(keys.KeyContainer)); if (!string.IsNullOrEmpty(keys.KeyFilePath)) { Sign(filePath, keys.KeyPair); } else { Sign(filePath, keys.KeyContainer!); } } internal override void SignBuilder(ExtendedPEBuilder peBuilder, BlobBuilder peBlob, RSAParameters privateKey) { peBuilder.Sign(peBlob, content => SigningUtilities.CalculateRsaSignature(content, privateKey)); } // EDMAURER in the event that the key is supplied as a file, // this type could get an instance member that caches the file // contents to avoid reading the file twice - once to get the // public key to establish the assembly name and another to do // the actual signing internal virtual IClrStrongName GetStrongNameInterface() { try { return ClrStrongName.GetInstance(); } catch (MarshalDirectiveException) when (PathUtilities.IsUnixLikePlatform) { // CoreCLR, when not on Windows, doesn't support IClrStrongName (or COM in general). // This is really hard to detect/predict without false positives/negatives. // It turns out that CoreCLR throws a MarshalDirectiveException when attempting // to get the interface (Message "Cannot marshal 'return value': Unknown error."), // so just catch that and state that it's not supported. // We're deep in a try block that reports the exception's Message as part of a diagnostic. // This exception will skip through the IOException wrapping by `Sign` (in this class), // then caught by Compilation.SerializeToPeStream or DesktopStringNameProvider.CreateKeys throw new ClrStrongNameMissingException(); } } internal ImmutableArray<byte> GetPublicKey(string keyContainer) { IClrStrongName strongName = GetStrongNameInterface(); IntPtr keyBlob; int keyBlobByteCount; strongName.StrongNameGetPublicKey(keyContainer, pbKeyBlob: default, 0, out keyBlob, out keyBlobByteCount); byte[] pubKey = new byte[keyBlobByteCount]; Marshal.Copy(keyBlob, pubKey, 0, keyBlobByteCount); strongName.StrongNameFreeBuffer(keyBlob); return pubKey.AsImmutableOrNull(); } /// <exception cref="IOException"/> private void Sign(string filePath, string keyName) { try { IClrStrongName strongName = GetStrongNameInterface(); strongName.StrongNameSignatureGeneration(filePath, keyName, IntPtr.Zero, 0, null, pcbSignatureBlob: out _); } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } private unsafe void Sign(string filePath, ImmutableArray<byte> keyPair) { try { IClrStrongName strongName = GetStrongNameInterface(); fixed (byte* pinned = keyPair.ToArray()) { strongName.StrongNameSignatureGeneration(filePath, null, (IntPtr)pinned, keyPair.Length, null, pcbSignatureBlob: out _); } } catch (ClrStrongNameMissingException) { // pipe it through so it's catchable directly by type throw; } catch (Exception ex) { throw new IOException(ex.Message, ex); } } public override int GetHashCode() { return Hash.CombineValues(_keyFileSearchPaths, StringComparer.Ordinal); } public override bool Equals(object? obj) { if (obj is null || GetType() != obj.GetType()) { return false; } var other = (DesktopStrongNameProvider)obj; if (FileSystem != other.FileSystem) { return false; } if (!_keyFileSearchPaths.SequenceEqual(other._keyFileSearchPaths, StringComparer.Ordinal)) { return false; } return true; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/Core/Portable/Shared/Extensions/IFindReferencesResultExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class IFindReferencesResultExtensions { public static IEnumerable<Location> GetDefinitionLocationsToShow( this ISymbol definition) { return definition.IsKind(SymbolKind.Namespace) ? SpecializedCollections.SingletonEnumerable(definition.Locations.First()) : definition.Locations; } public static ImmutableArray<ReferencedSymbol> FilterToItemsToShow( this ImmutableArray<ReferencedSymbol> result, FindReferencesSearchOptions options) { return result.WhereAsArray(r => ShouldShow(r, options)); } public static bool ShouldShow( this ReferencedSymbol referencedSymbol, FindReferencesSearchOptions options) { // If the reference has any locations then we will present it. if (referencedSymbol.Locations.Any()) { return true; } return referencedSymbol.Definition.ShouldShowWithNoReferenceLocations( options, showMetadataSymbolsWithoutReferences: true); } public static bool ShouldShowWithNoReferenceLocations( this ISymbol definition, FindReferencesSearchOptions options, bool showMetadataSymbolsWithoutReferences) { // If the definition is implicit and we have no references, then we don't want to // clutter the UI with it. if (definition.IsImplicitlyDeclared) { return false; } // If we're associating property references with an accessor, then we don't want to show // a property if it is has no references. Similarly, if we're associated associating // everything with the property, then we don't want to include accessors if there are no // references to them. if (options.AssociatePropertyReferencesWithSpecificAccessor) { if (definition.Kind == SymbolKind.Property) { return false; } } else { if (definition.IsPropertyAccessor()) { return false; } } // Otherwise we still show the item even if there are no references to it. // And it's at least a source definition. if (definition.Locations.Any(loc => loc.IsInSource)) { return true; } if (showMetadataSymbolsWithoutReferences && definition.Locations.Any(loc => loc.IsInMetadata)) { return true; } return false; } public static ImmutableArray<ReferencedSymbol> FilterToAliasMatches( this ImmutableArray<ReferencedSymbol> result, IAliasSymbol? aliasSymbol) { if (aliasSymbol == null) { return result; } var q = from r in result let aliasLocations = r.Locations.Where(loc => SymbolEquivalenceComparer.Instance.Equals(loc.Alias, aliasSymbol)).ToImmutableArray() where aliasLocations.Any() select new ReferencedSymbol(r.Definition, aliasLocations); return q.ToImmutableArray(); } public static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNames( this ImmutableArray<ReferencedSymbol> result, Solution solution, ISymbol symbol) { return symbol.IsOrdinaryMethod() ? FilterNonMatchingMethodNamesWorker(result, solution, symbol) : result; } private static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNamesWorker( ImmutableArray<ReferencedSymbol> references, Solution solution, ISymbol symbol) { using var _ = ArrayBuilder<ReferencedSymbol>.GetInstance(out var result); foreach (var reference in references) { var isCaseSensitive = solution.Workspace.Services.GetLanguageServices(reference.Definition.Language).GetRequiredService<ISyntaxFactsService>().IsCaseSensitive; var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; if (reference.Definition.IsOrdinaryMethod() && !comparer.Equals(reference.Definition.Name, symbol.Name)) { continue; } result.Add(reference); } return result.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class IFindReferencesResultExtensions { public static IEnumerable<Location> GetDefinitionLocationsToShow( this ISymbol definition) { return definition.IsKind(SymbolKind.Namespace) ? SpecializedCollections.SingletonEnumerable(definition.Locations.First()) : definition.Locations; } public static ImmutableArray<ReferencedSymbol> FilterToItemsToShow( this ImmutableArray<ReferencedSymbol> result, FindReferencesSearchOptions options) { return result.WhereAsArray(r => ShouldShow(r, options)); } public static bool ShouldShow( this ReferencedSymbol referencedSymbol, FindReferencesSearchOptions options) { // If the reference has any locations then we will present it. if (referencedSymbol.Locations.Any()) { return true; } return referencedSymbol.Definition.ShouldShowWithNoReferenceLocations( options, showMetadataSymbolsWithoutReferences: true); } public static bool ShouldShowWithNoReferenceLocations( this ISymbol definition, FindReferencesSearchOptions options, bool showMetadataSymbolsWithoutReferences) { // If the definition is implicit and we have no references, then we don't want to // clutter the UI with it. if (definition.IsImplicitlyDeclared) { return false; } // If we're associating property references with an accessor, then we don't want to show // a property if it is has no references. Similarly, if we're associated associating // everything with the property, then we don't want to include accessors if there are no // references to them. if (options.AssociatePropertyReferencesWithSpecificAccessor) { if (definition.Kind == SymbolKind.Property) { return false; } } else { if (definition.IsPropertyAccessor()) { return false; } } // Otherwise we still show the item even if there are no references to it. // And it's at least a source definition. if (definition.Locations.Any(loc => loc.IsInSource)) { return true; } if (showMetadataSymbolsWithoutReferences && definition.Locations.Any(loc => loc.IsInMetadata)) { return true; } return false; } public static ImmutableArray<ReferencedSymbol> FilterToAliasMatches( this ImmutableArray<ReferencedSymbol> result, IAliasSymbol? aliasSymbol) { if (aliasSymbol == null) { return result; } var q = from r in result let aliasLocations = r.Locations.Where(loc => SymbolEquivalenceComparer.Instance.Equals(loc.Alias, aliasSymbol)).ToImmutableArray() where aliasLocations.Any() select new ReferencedSymbol(r.Definition, aliasLocations); return q.ToImmutableArray(); } public static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNames( this ImmutableArray<ReferencedSymbol> result, Solution solution, ISymbol symbol) { return symbol.IsOrdinaryMethod() ? FilterNonMatchingMethodNamesWorker(result, solution, symbol) : result; } private static ImmutableArray<ReferencedSymbol> FilterNonMatchingMethodNamesWorker( ImmutableArray<ReferencedSymbol> references, Solution solution, ISymbol symbol) { using var _ = ArrayBuilder<ReferencedSymbol>.GetInstance(out var result); foreach (var reference in references) { var isCaseSensitive = solution.Workspace.Services.GetLanguageServices(reference.Definition.Language).GetRequiredService<ISyntaxFactsService>().IsCaseSensitive; var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; if (reference.Definition.IsOrdinaryMethod() && !comparer.Equals(reference.Definition.Name, symbol.Name)) { continue; } result.Add(reference); } return result.ToImmutable(); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/CSharp/Portable/Errors/DiagnosticInfoWithSymbols.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal class DiagnosticInfoWithSymbols : DiagnosticInfo { // not serialized: internal readonly ImmutableArray<Symbol> Symbols; internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, (int)errorCode, arguments) { this.Symbols = symbols; } internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments) { this.Symbols = symbols; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal class DiagnosticInfoWithSymbols : DiagnosticInfo { // not serialized: internal readonly ImmutableArray<Symbol> Symbols; internal DiagnosticInfoWithSymbols(ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, (int)errorCode, arguments) { this.Symbols = symbols; } internal DiagnosticInfoWithSymbols(bool isWarningAsError, ErrorCode errorCode, object[] arguments, ImmutableArray<Symbol> symbols) : base(CSharp.MessageProvider.Instance, isWarningAsError, (int)errorCode, arguments) { this.Symbols = symbols; } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/CSharp/Portable/Binder/FixedStatementBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class FixedStatementBinder : LocalScopeBinder { private readonly FixedStatementSyntax _syntax; public FixedStatementBinder(Binder enclosing, FixedStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { if (_syntax.Declaration != null) { var locals = new ArrayBuilder<LocalSymbol>(_syntax.Declaration.Variables.Count); _syntax.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (VariableDeclaratorSyntax declarator in _syntax.Declaration.Variables) { locals.Add(MakeLocal(_syntax.Declaration, declarator, LocalDeclarationKind.FixedVariable)); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, declarator); } return locals.ToImmutable(); } return ImmutableArray<LocalSymbol>.Empty; } 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; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class FixedStatementBinder : LocalScopeBinder { private readonly FixedStatementSyntax _syntax; public FixedStatementBinder(Binder enclosing, FixedStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { if (_syntax.Declaration != null) { var locals = new ArrayBuilder<LocalSymbol>(_syntax.Declaration.Variables.Count); _syntax.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { ExpressionVariableFinder.FindExpressionVariables(args.binder, args.locals, size); } } }, (binder: this, locals: locals)); foreach (VariableDeclaratorSyntax declarator in _syntax.Declaration.Variables) { locals.Add(MakeLocal(_syntax.Declaration, declarator, LocalDeclarationKind.FixedVariable)); // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionVariableFinder.FindExpressionVariables(this, locals, declarator); } return locals.ToImmutable(); } return ImmutableArray<LocalSymbol>.Empty; } 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; } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Server/VBCSCompiler/BuildProtocolUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { internal static class BuildProtocolUtil { internal static RunRequest GetRunRequest(BuildRequest req) { string? currentDirectory; string? libDirectory; string? tempDirectory; string[] arguments = GetCommandLineArguments(req, out currentDirectory, out tempDirectory, out libDirectory); string language = ""; switch (req.Language) { case RequestLanguage.CSharpCompile: language = LanguageNames.CSharp; break; case RequestLanguage.VisualBasicCompile: language = LanguageNames.VisualBasic; break; } return new RunRequest(req.RequestId, language, currentDirectory, tempDirectory, libDirectory, arguments); } internal static string[] GetCommandLineArguments(BuildRequest req, out string? currentDirectory, out string? tempDirectory, out string? libDirectory) { currentDirectory = null; libDirectory = null; tempDirectory = null; List<string> commandLineArguments = new List<string>(); foreach (BuildRequest.Argument arg in req.Arguments) { if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.CurrentDirectory) { currentDirectory = arg.Value; } else if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.TempDirectory) { tempDirectory = arg.Value; } else if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.LibEnvVariable) { libDirectory = arg.Value; } else if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.CommandLineArgument) { if (arg.Value is object) { int argIndex = arg.ArgumentIndex; while (argIndex >= commandLineArguments.Count) commandLineArguments.Add(""); commandLineArguments[argIndex] = arg.Value; } } } return commandLineArguments.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.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { internal static class BuildProtocolUtil { internal static RunRequest GetRunRequest(BuildRequest req) { string? currentDirectory; string? libDirectory; string? tempDirectory; string[] arguments = GetCommandLineArguments(req, out currentDirectory, out tempDirectory, out libDirectory); string language = ""; switch (req.Language) { case RequestLanguage.CSharpCompile: language = LanguageNames.CSharp; break; case RequestLanguage.VisualBasicCompile: language = LanguageNames.VisualBasic; break; } return new RunRequest(req.RequestId, language, currentDirectory, tempDirectory, libDirectory, arguments); } internal static string[] GetCommandLineArguments(BuildRequest req, out string? currentDirectory, out string? tempDirectory, out string? libDirectory) { currentDirectory = null; libDirectory = null; tempDirectory = null; List<string> commandLineArguments = new List<string>(); foreach (BuildRequest.Argument arg in req.Arguments) { if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.CurrentDirectory) { currentDirectory = arg.Value; } else if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.TempDirectory) { tempDirectory = arg.Value; } else if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.LibEnvVariable) { libDirectory = arg.Value; } else if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.CommandLineArgument) { if (arg.Value is object) { int argIndex = arg.ArgumentIndex; while (argIndex >= commandLineArguments.Count) commandLineArguments.Add(""); commandLineArguments[argIndex] = arg.Value; } } } return commandLineArguments.ToArray(); } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Compilers/Core/Portable/InternalUtilities/NoThrowStreamDisposer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// Catches exceptions thrown during disposal of the underlying stream and /// writes them to the given <see cref="TextWriter"/>. Check /// <see cref="HasFailedToDispose" /> after disposal to see if any /// exceptions were thrown during disposal. /// </summary> internal class NoThrowStreamDisposer : IDisposable { private bool? _failed; // Nullable to assert that this is only checked after dispose private readonly string _filePath; private readonly DiagnosticBag _diagnostics; private readonly CommonMessageProvider _messageProvider; /// <summary> /// Underlying stream /// </summary> public Stream Stream { get; } /// <summary> /// True if and only if an exception was thrown during a call to <see cref="Dispose"/> /// </summary> public bool HasFailedToDispose { get { RoslynDebug.Assert(_failed != null); return _failed.GetValueOrDefault(); } } public NoThrowStreamDisposer( Stream stream, string filePath, DiagnosticBag diagnostics, CommonMessageProvider messageProvider) { Stream = stream; _failed = null; _filePath = filePath; _diagnostics = diagnostics; _messageProvider = messageProvider; } public void Dispose() { RoslynDebug.Assert(_failed == null); try { Stream.Dispose(); if (_failed == null) { _failed = false; } } catch (Exception e) { _messageProvider.ReportStreamWriteException(e, _filePath, _diagnostics); // Record if any exceptions are thrown during dispose _failed = 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.IO; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// Catches exceptions thrown during disposal of the underlying stream and /// writes them to the given <see cref="TextWriter"/>. Check /// <see cref="HasFailedToDispose" /> after disposal to see if any /// exceptions were thrown during disposal. /// </summary> internal class NoThrowStreamDisposer : IDisposable { private bool? _failed; // Nullable to assert that this is only checked after dispose private readonly string _filePath; private readonly DiagnosticBag _diagnostics; private readonly CommonMessageProvider _messageProvider; /// <summary> /// Underlying stream /// </summary> public Stream Stream { get; } /// <summary> /// True if and only if an exception was thrown during a call to <see cref="Dispose"/> /// </summary> public bool HasFailedToDispose { get { RoslynDebug.Assert(_failed != null); return _failed.GetValueOrDefault(); } } public NoThrowStreamDisposer( Stream stream, string filePath, DiagnosticBag diagnostics, CommonMessageProvider messageProvider) { Stream = stream; _failed = null; _filePath = filePath; _diagnostics = diagnostics; _messageProvider = messageProvider; } public void Dispose() { RoslynDebug.Assert(_failed == null); try { Stream.Dispose(); if (_failed == null) { _failed = false; } } catch (Exception e) { _messageProvider.ReportStreamWriteException(e, _filePath, _diagnostics); // Record if any exceptions are thrown during dispose _failed = true; } } } }
-1
dotnet/roslyn
56,460
Set CompilerApiVersion in Microsoft.Managed.Core.targets
This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
eerhardt
"2021-09-16T21:47:36Z"
"2021-09-22T00:53:07Z"
a10a3720229de8f4227e98736e884d6f926a9950
aabc2fcbf630ba303e6f17808465349ea9b01a32
Set CompilerApiVersion in Microsoft.Managed.Core.targets. This allows other targets to understand which compiler will be used. This is useful in the SDK targets that need figure out the version in order to pick the right analyzer assets. Contributes to #52265 FYI - @dsplaisted. This resolves the feedback from https://github.com/dotnet/sdk/pull/20793#discussion_r707788803
./src/Workspaces/Core/MSBuild/MSBuild/ProjectMap.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A map of projects that can be optionally used with <see cref="MSBuildProjectLoader.LoadProjectInfoAsync"/> when loading a /// project into a custom <see cref="Workspace"/>. To use, pass <see cref="Workspace.CurrentSolution"/> to <see cref="Create(Solution)"/>. /// </summary> public class ProjectMap { /// <summary> /// A map of project path to <see cref="ProjectId"/>s. Note that there can be multiple <see cref="ProjectId"/>s per project path /// if the project is multi-targeted -- one for each target framework. /// </summary> private readonly Dictionary<string, HashSet<ProjectId>> _projectPathToProjectIdsMap; /// <summary> /// A map of project path to <see cref="ProjectInfo"/>s. Note that there can be multiple <see cref="ProjectId"/>s per project path /// if the project is multi-targeted -- one for each target framework. /// </summary> private readonly Dictionary<string, ImmutableArray<ProjectInfo>> _projectPathToProjectInfosMap; /// <summary> /// A map of <see cref="ProjectId"/> to the output file of the project (if any). /// </summary> private readonly Dictionary<ProjectId, string> _projectIdToOutputFilePathMap; /// <summary> /// A map of <see cref="ProjectId"/> to the output ref file of the project (if any). /// </summary> private readonly Dictionary<ProjectId, string> _projectIdToOutputRefFilePathMap; private ProjectMap() { _projectPathToProjectIdsMap = new Dictionary<string, HashSet<ProjectId>>(PathUtilities.Comparer); _projectPathToProjectInfosMap = new Dictionary<string, ImmutableArray<ProjectInfo>>(PathUtilities.Comparer); _projectIdToOutputFilePathMap = new Dictionary<ProjectId, string>(); _projectIdToOutputRefFilePathMap = new Dictionary<ProjectId, string>(); } /// <summary> /// Create an empty <see cref="ProjectMap"/>. /// </summary> public static ProjectMap Create() => new(); /// <summary> /// Create a <see cref="ProjectMap"/> populated with the given <see cref="Solution"/>. /// </summary> /// <param name="solution">The <see cref="Solution"/> to populate the new <see cref="ProjectMap"/> with.</param> /// <returns></returns> public static ProjectMap Create(Solution solution) { var projectMap = new ProjectMap(); foreach (var project in solution.Projects) { projectMap.Add(project); } return projectMap; } /// <summary> /// Add a <see cref="Project"/> to this <see cref="ProjectMap"/>. /// </summary> /// <param name="project">The <see cref="Project"/> to add to this <see cref="ProjectMap"/>.</param> public void Add(Project project) { Add(project.Id, project.FilePath, project.OutputFilePath, project.OutputRefFilePath); AddProjectInfo(project.State.ProjectInfo); } private void Add(ProjectId projectId, string? projectPath, string? outputFilePath, string? outputRefFilePath) { if (!RoslynString.IsNullOrEmpty(projectPath)) { _projectPathToProjectIdsMap.MultiAdd(projectPath, projectId); } if (!RoslynString.IsNullOrEmpty(outputFilePath)) { _projectIdToOutputFilePathMap.Add(projectId, outputFilePath); } if (!RoslynString.IsNullOrEmpty(outputRefFilePath)) { _projectIdToOutputRefFilePathMap.Add(projectId, outputRefFilePath); } } internal void AddProjectInfo(ProjectInfo projectInfo) { var projectFilePath = projectInfo.FilePath; if (RoslynString.IsNullOrEmpty(projectFilePath)) { throw new ArgumentException(WorkspaceMSBuildResources.Project_does_not_have_a_path); } if (!_projectPathToProjectInfosMap.TryGetValue(projectFilePath, out var projectInfos)) { projectInfos = ImmutableArray<ProjectInfo>.Empty; } if (projectInfos.Contains(pi => pi.Id == projectInfo.Id)) { throw new ArgumentException(WorkspaceMSBuildResources.Project_already_added); } projectInfos = projectInfos.Add(projectInfo); _projectPathToProjectInfosMap[projectFilePath] = projectInfos; } private ProjectId CreateProjectId(string? projectPath, string? outputFilePath, string? outputRefFilePath) { var newProjectId = ProjectId.CreateNewId(debugName: projectPath); Add(newProjectId, projectPath, outputFilePath, outputRefFilePath); return newProjectId; } internal ProjectId GetOrCreateProjectId(string projectPath) { if (!_projectPathToProjectIdsMap.TryGetValue(projectPath, out var projectIds)) { projectIds = new HashSet<ProjectId>(); _projectPathToProjectIdsMap.Add(projectPath, projectIds); } return projectIds.Count == 1 ? projectIds.Single() : CreateProjectId(projectPath, outputFilePath: null, outputRefFilePath: null); } internal ProjectId GetOrCreateProjectId(ProjectFileInfo projectFileInfo) { var projectPath = projectFileInfo.FilePath; var outputFilePath = projectFileInfo.OutputFilePath; var outputRefFilePath = projectFileInfo.OutputRefFilePath; if (projectPath is not null && TryGetIdsByProjectPath(projectPath, out var projectIds)) { if (TryFindOutputFileRefPathInProjectIdSet(outputRefFilePath, projectIds, out var projectId) || TryFindOutputFilePathInProjectIdSet(outputFilePath, projectIds, out projectId)) { return projectId; } } return CreateProjectId(projectPath, outputFilePath, outputRefFilePath); } private bool TryFindOutputFileRefPathInProjectIdSet(string? outputRefFilePath, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) => TryFindPathInProjectIdSet(outputRefFilePath, GetOutputRefFilePathById, set, out result); private bool TryFindOutputFilePathInProjectIdSet(string? outputFilePath, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) => TryFindPathInProjectIdSet(outputFilePath, GetOutputFilePathById, set, out result); private static bool TryFindPathInProjectIdSet(string? path, Func<ProjectId, string?> getPathById, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) { if (!RoslynString.IsNullOrEmpty(path)) { foreach (var id in set) { var p = getPathById(id); if (PathUtilities.Comparer.Equals(p, path)) { result = id; return true; } } } result = null; return false; } internal string? GetOutputRefFilePathById(ProjectId projectId) => TryGetOutputRefFilePathById(projectId, out var path) ? path : null; internal string? GetOutputFilePathById(ProjectId projectId) => TryGetOutputFilePathById(projectId, out var path) ? path : null; internal bool TryGetIdsByProjectPath(string projectPath, [NotNullWhen(true)] out HashSet<ProjectId>? ids) => _projectPathToProjectIdsMap.TryGetValue(projectPath, out ids); internal bool TryGetOutputFilePathById(ProjectId id, [NotNullWhen(true)] out string? outputFilePath) => _projectIdToOutputFilePathMap.TryGetValue(id, out outputFilePath); internal bool TryGetOutputRefFilePathById(ProjectId id, [NotNullWhen(true)] out string? outputRefFilePath) => _projectIdToOutputRefFilePathMap.TryGetValue(id, out outputRefFilePath); internal bool TryGetProjectInfosByProjectPath(string projectPath, out ImmutableArray<ProjectInfo> projectInfos) => _projectPathToProjectInfosMap.TryGetValue(projectPath, out projectInfos); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A map of projects that can be optionally used with <see cref="MSBuildProjectLoader.LoadProjectInfoAsync"/> when loading a /// project into a custom <see cref="Workspace"/>. To use, pass <see cref="Workspace.CurrentSolution"/> to <see cref="Create(Solution)"/>. /// </summary> public class ProjectMap { /// <summary> /// A map of project path to <see cref="ProjectId"/>s. Note that there can be multiple <see cref="ProjectId"/>s per project path /// if the project is multi-targeted -- one for each target framework. /// </summary> private readonly Dictionary<string, HashSet<ProjectId>> _projectPathToProjectIdsMap; /// <summary> /// A map of project path to <see cref="ProjectInfo"/>s. Note that there can be multiple <see cref="ProjectId"/>s per project path /// if the project is multi-targeted -- one for each target framework. /// </summary> private readonly Dictionary<string, ImmutableArray<ProjectInfo>> _projectPathToProjectInfosMap; /// <summary> /// A map of <see cref="ProjectId"/> to the output file of the project (if any). /// </summary> private readonly Dictionary<ProjectId, string> _projectIdToOutputFilePathMap; /// <summary> /// A map of <see cref="ProjectId"/> to the output ref file of the project (if any). /// </summary> private readonly Dictionary<ProjectId, string> _projectIdToOutputRefFilePathMap; private ProjectMap() { _projectPathToProjectIdsMap = new Dictionary<string, HashSet<ProjectId>>(PathUtilities.Comparer); _projectPathToProjectInfosMap = new Dictionary<string, ImmutableArray<ProjectInfo>>(PathUtilities.Comparer); _projectIdToOutputFilePathMap = new Dictionary<ProjectId, string>(); _projectIdToOutputRefFilePathMap = new Dictionary<ProjectId, string>(); } /// <summary> /// Create an empty <see cref="ProjectMap"/>. /// </summary> public static ProjectMap Create() => new(); /// <summary> /// Create a <see cref="ProjectMap"/> populated with the given <see cref="Solution"/>. /// </summary> /// <param name="solution">The <see cref="Solution"/> to populate the new <see cref="ProjectMap"/> with.</param> /// <returns></returns> public static ProjectMap Create(Solution solution) { var projectMap = new ProjectMap(); foreach (var project in solution.Projects) { projectMap.Add(project); } return projectMap; } /// <summary> /// Add a <see cref="Project"/> to this <see cref="ProjectMap"/>. /// </summary> /// <param name="project">The <see cref="Project"/> to add to this <see cref="ProjectMap"/>.</param> public void Add(Project project) { Add(project.Id, project.FilePath, project.OutputFilePath, project.OutputRefFilePath); AddProjectInfo(project.State.ProjectInfo); } private void Add(ProjectId projectId, string? projectPath, string? outputFilePath, string? outputRefFilePath) { if (!RoslynString.IsNullOrEmpty(projectPath)) { _projectPathToProjectIdsMap.MultiAdd(projectPath, projectId); } if (!RoslynString.IsNullOrEmpty(outputFilePath)) { _projectIdToOutputFilePathMap.Add(projectId, outputFilePath); } if (!RoslynString.IsNullOrEmpty(outputRefFilePath)) { _projectIdToOutputRefFilePathMap.Add(projectId, outputRefFilePath); } } internal void AddProjectInfo(ProjectInfo projectInfo) { var projectFilePath = projectInfo.FilePath; if (RoslynString.IsNullOrEmpty(projectFilePath)) { throw new ArgumentException(WorkspaceMSBuildResources.Project_does_not_have_a_path); } if (!_projectPathToProjectInfosMap.TryGetValue(projectFilePath, out var projectInfos)) { projectInfos = ImmutableArray<ProjectInfo>.Empty; } if (projectInfos.Contains(pi => pi.Id == projectInfo.Id)) { throw new ArgumentException(WorkspaceMSBuildResources.Project_already_added); } projectInfos = projectInfos.Add(projectInfo); _projectPathToProjectInfosMap[projectFilePath] = projectInfos; } private ProjectId CreateProjectId(string? projectPath, string? outputFilePath, string? outputRefFilePath) { var newProjectId = ProjectId.CreateNewId(debugName: projectPath); Add(newProjectId, projectPath, outputFilePath, outputRefFilePath); return newProjectId; } internal ProjectId GetOrCreateProjectId(string projectPath) { if (!_projectPathToProjectIdsMap.TryGetValue(projectPath, out var projectIds)) { projectIds = new HashSet<ProjectId>(); _projectPathToProjectIdsMap.Add(projectPath, projectIds); } return projectIds.Count == 1 ? projectIds.Single() : CreateProjectId(projectPath, outputFilePath: null, outputRefFilePath: null); } internal ProjectId GetOrCreateProjectId(ProjectFileInfo projectFileInfo) { var projectPath = projectFileInfo.FilePath; var outputFilePath = projectFileInfo.OutputFilePath; var outputRefFilePath = projectFileInfo.OutputRefFilePath; if (projectPath is not null && TryGetIdsByProjectPath(projectPath, out var projectIds)) { if (TryFindOutputFileRefPathInProjectIdSet(outputRefFilePath, projectIds, out var projectId) || TryFindOutputFilePathInProjectIdSet(outputFilePath, projectIds, out projectId)) { return projectId; } } return CreateProjectId(projectPath, outputFilePath, outputRefFilePath); } private bool TryFindOutputFileRefPathInProjectIdSet(string? outputRefFilePath, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) => TryFindPathInProjectIdSet(outputRefFilePath, GetOutputRefFilePathById, set, out result); private bool TryFindOutputFilePathInProjectIdSet(string? outputFilePath, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) => TryFindPathInProjectIdSet(outputFilePath, GetOutputFilePathById, set, out result); private static bool TryFindPathInProjectIdSet(string? path, Func<ProjectId, string?> getPathById, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) { if (!RoslynString.IsNullOrEmpty(path)) { foreach (var id in set) { var p = getPathById(id); if (PathUtilities.Comparer.Equals(p, path)) { result = id; return true; } } } result = null; return false; } internal string? GetOutputRefFilePathById(ProjectId projectId) => TryGetOutputRefFilePathById(projectId, out var path) ? path : null; internal string? GetOutputFilePathById(ProjectId projectId) => TryGetOutputFilePathById(projectId, out var path) ? path : null; internal bool TryGetIdsByProjectPath(string projectPath, [NotNullWhen(true)] out HashSet<ProjectId>? ids) => _projectPathToProjectIdsMap.TryGetValue(projectPath, out ids); internal bool TryGetOutputFilePathById(ProjectId id, [NotNullWhen(true)] out string? outputFilePath) => _projectIdToOutputFilePathMap.TryGetValue(id, out outputFilePath); internal bool TryGetOutputRefFilePathById(ProjectId id, [NotNullWhen(true)] out string? outputRefFilePath) => _projectIdToOutputRefFilePathMap.TryGetValue(id, out outputRefFilePath); internal bool TryGetProjectInfosByProjectPath(string projectPath, out ImmutableArray<ProjectInfo> projectInfos) => _projectPathToProjectInfosMap.TryGetValue(projectPath, out projectInfos); } }
-1